Asp.net.WebForm的DropDownList下拉框如何绑定数据源

今天学习下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>

运行后效果图

平时多记记,到用时才能看看,记录你的进步,分享你的成果
原文地址:https://www.cnblogs.com/xielong/p/15219317.html