How to SELECT a drop down list item by value programatically in C#.NET?
+5
A:
myDropDown.SelectedIndex =
myDropDown.Items.IndexOf(myDropDown.Items.FindByValue("myValue"))
womp
2009-08-08 17:23:00
The value is becoming -1 in the myDropDown.SelectedIndex why?
David Bonnici
2009-08-08 17:28:02
probably because myDropDown.Items haven't an item "myValue"
Arnis L.
2009-08-08 17:48:00
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
2009-08-08 17:48:56
+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
2009-08-08 17:44:09