2011-11-01 165 views
8

我在我的網頁上有一個下拉列表控件。我已經將DataTable綁定到下拉列表控件,如下所示 -如何將默認值設置爲下拉列表控件?

lstDepartment.DataTextField = "DepartmentName"; 
    lstDepartment.DataValueField = "DepartmentID"; 
    lstDepartment.DataSource = dtDept; 
    lstDepartment.DataBind(); 
在頁面加載事件我想設置的默認值下拉列表控制從我的其他表字段

該怎麼辦?

回答

0

假設在其他表DropDownList控件還包含DepartmentName的和DepartmentID的:

lstDepartment.ClearSelection(); 

foreach (var item in lstDepartment.Items) 
{ 
    if (item.Value == otherDropDownList.SelectedValue) 
    { 
    item.Selected = true; 
    } 
}
22

後您的DataBind()

lstDepartment.SelectedIndex = 0; //first item 

or 

lstDepartment.SelectedValue = "Yourvalue" 

or 
//add error checking, just an example, FindByValue may return null 
lstDepartment.Items.FindByValue("Yourvalue").Selected = true; 

or 
//add error checking, just an example, FindByText may return null 
lstDepartment.Items.FindByText("Yourvalue").Selected = true; 
+0

其確切的工作我想要什麼。如果值不存在,那麼我想設置爲空白記錄。這個怎麼做? – Priyanka

+1

lstDepartment.Items.Insert(0,new ListItem(「」,「」)); –

+1

我已將數據表綁定到下拉列表。我用你的代碼將默認值設置爲空白。但是它也顯示了表中的第0條記錄。 – Priyanka

4

,如果你知道缺省值的項目的索引,只

lstDepartment.SelectedIndex = 1;//the second item 

或者如果你知道你想設置的值,只需要

lstDepartment.SelectedValue = "the value you want to set"; 
0
lstDepartment.DataTextField = "DepartmentName"; 
lstDepartment.DataValueField = "DepartmentID"; 
lstDepartment.DataSource = dtDept; 
lstDepartment.DataBind(); 
'Set the initial value: 
lstDepartment.SelectedValue = depID; 
lstDepartment.Attributes.Remove("InitialValue"); 
lstDepartment.Attributes.Add("InitialValue", depID); 

而在你的取消方法:

lstDepartment.SelectedValue = lstDepartment.Attributes("InitialValue"); 

並在您更新方法:

lstDepartment.Attributes("InitialValue") = lstDepartment.SelectedValue; 
相關問題