这几天遇到再DropDownList中,如何将数据库中的内容与DropDownList下拉框中的值关联起来,步骤如下:
(1)建立要关联的数据库(在本例中假设为dept);
要定义一个数据表用来取得这个表中的内容,代码如下:
public DataTableReader SelectDept()
{
DataTableReader dr = null;
try
{
RunSQL("select * from dept",out dr);
}
catch(Exception ex)
{
throw new Exception(ex.Message, ex);
}
return (dr);
}
(2)设置
DropDownList2.DataSource = dep.SelectDept();//绑定到数据库中,这样可以动态修改教研室
DropDownList2.DataTextField = "dep";
DropDownList2.DataValueField = "id";
DropDownList2.DataBind();
记得要将这个绑定数据放在加载这个页面。
(3)测试页面如下: