Eyla Eyla - 1 year ago 101
ASP.NET (C#) Question

Setting dropdownlist selecteditem programmatically

I want to set the

attribute for an ASP.Net dropdownlist control programmatically.

So I want to pass a value to the dropdownlist control to set the selected item where the item is equal to the passed value.

Answer Source

Assuming the list is already data bound you can simply set the SelectedValue property on your dropdown list.

list.DataSource = GetListItems(); // <-- Get your data from somewhere.
list.DataValueField = "ValueProperty";
list.DataTextField = "TextProperty";

list.SelectedValue = myValue.ToString();

The value of the myValue variable would need to exist in the property specified within the DataValueField in your controls databinding.

UPDATE: If the value of myValue doesn't exist as a value with the dropdown list options it will default to select the first option in the dropdown list.