2014-09-23 60 views
2

我試圖從數據表中綁定dropdownlist,其中數據表包含departmentID和DepartmnentName。綁定成功,但如何設置項目的值?如何從數據表中設置dropdownlist的值?

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

回答

2

不要只是添加字符串,添加一個ListItem(這對於該公開more useful constructors):

DropDownList1.Items.Add(new ListItem(dr[1].ToString(), dr[0].ToString())); 
//         ^^--Text   ^^--Value 

(假設「價值」你想要的是在dr[0],只需使用任何持有您的代碼的實際值)

您也可以直接將控件綁定到DataTable,而不是在循環中添加項目。像這樣:

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