如何设置下拉列表控件的默认值

本文关键字:下拉列表 控件 默认值 设置 何设置 | 更新日期: 2023-09-27 18:13:23

我的网页上有一个下拉列表控件。我已经将数据表绑定到dropdownlist控件,如下所示-

lstDepartment.DataTextField = "DepartmentName";
    lstDepartment.DataValueField = "DepartmentID";
    lstDepartment.DataSource = dtDept;
    lstDepartment.DataBind();

在页面加载事件中,我想从我的另一个表字段中为下拉列表控件设置默认值。

如何做到这一点?

如何设置下拉列表控件的默认值

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;

如果您知道默认值项的索引,则仅

lstDepartment.SelectedIndex = 1;//the second item

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

lstDepartment.SelectedValue = "the value you want to set";

假设另一个表中的DropDownList控件也包含DepartmentName和DepartmentID:

lstDepartment.ClearSelection();
foreach (var item in lstDepartment.Items) 
{
  if (item.Value == otherDropDownList.SelectedValue)
  {
    item.Selected = true;
  }
}
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;