Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting dropdownlist selecteditem programmatically

I want to set the selecteditem 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.

like image 954
Eyla Avatar asked Aug 16 '10 19:08

Eyla


People also ask

How do I set the selected value in drop down?

The select tag in HTML is used to create a dropdown list of options that can be selected. The option tag contains the value that would be used when selected. The default value of the select element can be set by using the 'selected' attribute on the required option. This is a boolean attribute.


2 Answers

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.DataBind();  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.

like image 152
Wallace Breza Avatar answered Sep 26 '22 00:09

Wallace Breza


ddlData.SelectedIndex will contain the int value To select the specific value into DropDown :

ddlData.SelectedIndex=ddlData.Items.IndexOf(ddlData.Items.FindByText("value")); 

return type of ddlData.Items.IndexOf(ddlData.Items.FindByText("value")); is int.

like image 44
PrateekSaluja Avatar answered Sep 25 '22 00:09

PrateekSaluja