views:

1484

answers:

2

How to SELECT a drop down list item by value programatically in C#.NET?

See PIC

+5  A: 
myDropDown.SelectedIndex = 
    myDropDown.Items.IndexOf(myDropDown.Items.FindByValue("myValue"))
womp
The value is becoming -1 in the myDropDown.SelectedIndex why?
David Bonnici
probably because myDropDown.Items haven't an item "myValue"
Arnis L.
IndexOf() returns -1 if the item isn't in the collection. FindByValue() isn't finding the item you're looking for. Just break it apart into separate statements if you need to debug it.
womp
+2  A: 

If you know that the dropdownlist contains the value you're looking to select, use:

ddl.SelectedValue = "2";

If you're not sure if the value exists, use (or you'll get a null reference exception):

ListItem selectedListItem = ddl.Items.FindByValue("2");

if (selectedListItem != null)
{
    selectedListItem.Selected = true;
};
ScottE