我的网页上有一个下拉列表控件。我已将数据表绑定到dropdownlist控件,如下所示 -
lstDepartment.DataTextField = "DepartmentName";
lstDepartment.DataValueField = "DepartmentID";
lstDepartment.DataSource = dtDept;
lstDepartment.DataBind();
在页面加载事件中我想从我的其他表字段中将默认值设置为下拉列表控件。
怎么做?
答案 0 :(得分:26)
在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;
答案 1 :(得分:4)
如果您知道默认值项的索引,只需
lstDepartment.SelectedIndex = 1;//the second item
或者如果您知道要设置的值,只需
lstDepartment.SelectedValue = "the value you want to set";
答案 2 :(得分:0)
假设另一个表中的DropDownList控件还包含DepartmentName和DepartmentID:
lstDepartment.ClearSelection();
foreach (var item in lstDepartment.Items)
{
if (item.Value == otherDropDownList.SelectedValue)
{
item.Selected = true;
}
}
答案 3 :(得分: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;