How to SELECT a drop down list item by value programatically in C#.NET?
How to SELECT a drop down list item by value programatically in C#.NET?
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;
}
Please try below:
myDropDown.SelectedIndex =
myDropDown.Items.IndexOf(myDropDown.Items.FindByValue("myValue"))
combobox1.SelectedValue = x;
I suspect you may want yo hear something else, but this is what you asked for.
If anyone else is trying this and facing problem then let me point one possible problem: If you are using Web Application then inside Page_Load if you are loading drop-down from DB and at the sametime you want to load data, then first load your drop-down lists and then load your data with selected drop-down conditions.
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
LoadDropdown(); //drop-downs generated first
LoadData(); // other data loading and drop-down value selection logic here
}
}
And for successfully selecting drop-down from code follow the approved answer above which is
ddl.SelectedValue = "2";.
Hope it solves the problem