如何为C#后面的代码中的下拉列表动态设置值

时间:2011-07-01 05:49:25

标签: c# drop-down-menu

我需要动态地将值“Y”设置为dropdownlist控件。当我尝试使用selectedValue时,它给出了错误,如对象引用为null .plz help

3 个答案:

答案 0 :(得分:3)

首先确保asp:DropDownList内有Y。然后这样做

if (DropDownList1.Items.FindByValue("Y") != null)
{
     DropDownList1.Items.FindByValue("Y").Selected = true;
}

答案 1 :(得分:1)

假设您的下拉列表中有“Y”:

DropDownList1.SelectedValue = DropDownList1.Items.FindByValue( “Y”)的ToString();

有效。

答案 2 :(得分:0)

SelectedValue仅在使用数据绑定时有效。如果您通过Visual Studio中的Windows窗体设计器手动填写列表或操作DropDownList.Items集合,则需要使用SelectedItem,如下所示:

DropDownList1.SelectedItem = "Y";