今天學習下Asp.net.WebForm的DropDownlist下拉框控件如何綁定數據源,這個類似於html的下拉控件(<select> <option></option></select>)
1、在asp頁面進行直接使用
<form id="myForm" runat="server"> <!-- dropdownlist的直接使用 --> <asp:Label ID="labSex" Text=" 性別:" runat="server"></asp:Label> <asp:DropDownList ID="sexlist" runat="server"> <asp:ListItem Value="1">男</asp:ListItem> <asp:ListItem Value="0">女</asp:ListItem> </asp:DropDownList><br /> </form>
2、asp后台頁面綁定數據源
<form id="myForm" runat="server"> <!-- dropdownlist的后台綁定數據源 --> <asp:Label ID="labcountry" Text=" 國家(后台綁定)" runat="server"></asp:Label> <asp:DropDownList ID="countrylist" runat="server"> </asp:DropDownList><br /> </form>
后台頁面編寫綁定
protected void Page_Load(object sender, EventArgs e) { //獲取前20個國家列表數據 string strSql = string.Format("select Uid as value,Code as code,Name as text from sysCountry where Uid<=@Uid"); SqlParameter[] pars = { new SqlParameter("@Uid",20) }; //返回查詢結果 DataTable tabs = SqlHelper.ExcuteTable(strSql, pars); if (tabs.Rows.Count > 0) { //綁定數據庫查詢的數據源 this.countrylist.DataSource = tabs; this.countrylist.DataValueField = "value"; this.countrylist.DataTextField = "text"; this.countrylist.DataBind(); } }
3、通過數據庫連接綁定數據源
1)打開asp的設計頁面
2)選擇數據源(沒有連接,選擇新建連接)
3)選擇數據庫類型(選擇SQL數據庫)
4)選擇數據庫連接(選擇默認的SQL Server,沒有新建)
5)配置數據源的SQL語句(選擇數據表,需要的數據列等)
6)測試查詢
asp頁面(開始,未配置數據源)
<!-- dropdownlist的數據庫綁定數據源 --> <asp:Label ID="labconnect" Text=" 國家(數據庫連接綁定)" runat="server"></asp:Label> <asp:DropDownList ID="mylist" runat="server" ></asp:DropDownList>
asp頁面(結束,已配置數據源)
<!-- dropdownlist的數據庫綁定數據源 --> <asp:Label ID="labconnect" Text=" 國家(數據庫連接綁定)" runat="server"></asp:Label> <asp:DropDownList ID="mylist" runat="server" DataSourceID="SqlDataSource1" DataTextField="Name" DataValueField="Name"></asp:DropDownList> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="Data Source=.;Initial Catalog=CPAP_210831;Persist Security Info=True;User ID=sa;Password=sa" ProviderName="System.Data.SqlClient" SelectCommand="SELECT * FROM [sysCountry]"></asp:SqlDataSource>
運行后效果圖