views:

199

answers:

3

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 item equal to the passed value.

+2  A: 

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.

Wallace Breza
A: 

Here is the code I was looking for:

option one: DDL.SelectedIndex = DDL.Items.IndexOf(DDL.Items.FindByText("PassedValue"));

option two: DDL.SelectedIndex = DDL.Items.IndexOf(DDL.Items.FindByValue("PassedValue"));

Eyla
@Eyla - That's basically doing the same thing with more code. Even if the selected value doesn't exist as an item in the list it defaults to the first option as its selected value.
Wallace Breza
+6  A: 

Hello,

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 value.

Thanks

PrateekSaluja