C# 如何从数据表设置dropdownlist的值?

C# 如何从数据表设置dropdownlist的值?,c#,asp.net,ado.net,C#,Asp.net,Ado.net,我正在尝试从数据表绑定dropdownlist,其中数据表包含departmentID和departmentName。绑定成功,但如何设置项的值 dt = objDeparment.SelectAll().Tables[0]; foreach (DataRow dr in dt.Rows) { DropDownList1.Items.Add(dr[1].ToString()); //binding the dropdownlist with departm

我正在尝试从数据表绑定dropdownlist,其中数据表包含departmentID和departmentName。绑定成功,但如何设置项的值

    dt = objDeparment.SelectAll().Tables[0];
    foreach (DataRow dr in dt.Rows)
    {
        DropDownList1.Items.Add(dr[1].ToString()); //binding the dropdownlist with department names
    }

不要只添加字符串,还要添加一个
ListItem
(这将为此公开):

(假设您想要的“值”在
dr[0]
中,只需使用包含代码实际值的内容即可)

您还可以将控件直接绑定到
DataTable
,而不是在循环中添加项。大概是这样的:

DropDownList1.DataSource = objDeparment.SelectAll().Tables[0];
DropDownList1.DataTextField = "some column";
DropDownList1.DataValueField = "another column";
DropDownList1.DataBind();
DropDownList1.DataSource = objDeparment.SelectAll().Tables[0];
DropDownList1.DataTextField = "some column";
DropDownList1.DataValueField = "another column";
DropDownList1.DataBind();