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 设置要读取的列

 

 

posted on 2010-12-31 18:22  墟零  阅读(13421)  评论(0编辑  收藏  举报