How to set a value dynamically for dropdownlist in code behind C#
I need to set va开发者_如何学JAVAlue "Y" to dropdownlist control dynamically.When i tried by selectedValue it gave error like object reference is null .plz help
First make sure that Y is there inside your asp:DropDownList
. Then do this
if (DropDownList1.Items.FindByValue("Y") != null)
{
DropDownList1.Items.FindByValue("Y").Selected = true;
}
Assuming that "Y" is in your dropdownlist:
DropDownList1.SelectedValue=DropDownList1.Items.FindByValue("Y").Tostring();
It works.
SelectedValue
will only work when using data binding. If you filled out the list manually via the Windows Forms Designer in Visual Studio or by manipulating the DropDownList.Items
collection, you need to use SelectedItem
as below:
DropDownList1.SelectedItem = "Y";
精彩评论