I want to set selecteditem for asp. net dropdownlist control programmatically.
So I want to pass a value to the dropdownlist control to set the selected item where is the value of the item equal to the passed value.
You can set the SelectedValue to the value you want to select. If you already have selected item then you should clear the selection otherwise you would get "Cannot have multiple items selected in a DropDownList" error. dropdownlist. ClearSelection(); dropdownlist.
Using the jQuery change() method; you can set the selected value of dropdown in jquery by using id, name, class, and tag with selected html elements; see the following example for that: Example 1 :- Set selected value of dropdown in jquery by id.
cs. In order to be able to select an item and have the value updated to the database, in the DropDownList add the AutoPostBack property and set it to true. Then, add the OnSeletedIndexChanged property and choose the 'create new event' option. It will created a method automatically in the <filename>.
You have to use SelectedValue property of DropDownList . DataTextField and DataValueField are for specifying which properties from DataSource should be used as Text and Value of drop down list.
dropdownlist.ClearSelection(); //making sure the previous selection has been cleared dropdownlist.Items.FindByValue(value).Selected = true;
You can set the SelectedValue
to the value you want to select. If you already have selected item then you should clear the selection otherwise you would get "Cannot have multiple items selected in a DropDownList" error.
dropdownlist.ClearSelection(); dropdownlist.SelectedValue = value;
You can also use ListItemCollection.FindByText or ListItemCollection.FindByValue
dropdownlist.ClearSelection(); dropdownlist.Items.FindByValue(value).Selected = true;
Use the FindByValue method to search the collection for a ListItem with a Value property that contains value specified by the value parameter. This method performs a case-sensitive and culture-insensitive comparison. This method does not do partial searches or wildcard searches. If an item is not found in the collection using this criteria, null is returned, MSDN.
If you expect that you may be looking for text/value that wont be present in DropDownList
ListItem collection then you must check if you get the ListItem
object or null
from FindByText
or FindByValue
before you access Selected property. If you try to access Selected when null is returned then you will get NullReferenceException.
ListItem listItem = dropdownlist.Items.FindByValue(value); if(listItem != null) { dropdownlist.ClearSelection(); listItem.Selected = true; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With