DropDownList与DataTable数据绑定的方法

转自:https://www.cnblogs.com/fishtreeyu/archive/2010/12/31/1923362.html

aspx页面代码

<form id="form1" runat="server">
   <asp:DropDownList ID="DropDownList1" runat="server" Width="170px">
   </asp:DropDownList></div>
</form>

aspx.cs后台代码

protected void Page_Load(object sender, EventArgs e)
{
    //数据库连接
    SqlConnection conn = new SqlConnection("uid=用户名;pwd=用户密码;server=数据库IP地址;database=数据库名"");
    SqlCommand cmd = new SqlCommand("select * from Class",conn);
    //建立数据适配器、数据表并填充
    SqlDataAdapter adpt = new SqlDataAdapter(cmd);
    DataTable dtable = new DataTable();
    adpt.Fill(dtable);
    //★★与表的数据绑定★★
    DropDownList1.DataSource = dtable;//设置数据源
    DropDownList1.DataTextField = "ClassName";//设置所要读取的数据表里的列名
    DropDownList1.DataValueField = "ClassId";
    DropDownList1.DataBind();//数据绑定
}

DropDownList读取表格里的东西时候得记得用DropDownList1.DataTextField 设置要读取的列

猜你喜欢

转载自www.cnblogs.com/JesseP/p/11446668.html