The drop-down list setting is selected programmatically.

I want to programmatically set the selecteditem attribute for an ASP.Net dropdownlist control.

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

+60
c # drop-down-menu
Aug 16 '10 at 19:12
source share
8 answers

Assuming the list is already data bound, you can simply set the SelectedValue property in the drop-down 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 must exist in the property specified in the DataValueField in the data binding of the controls.

UPDATE : If the value myValue does not exist as a value with drop-down options, the first option in the drop-down list will be selected by default.

+84
Aug 16 '10 at 19:17
source share

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

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

return Type ddlData.Items.IndexOf(ddlData.Items.FindByText("value")); - int .

+54
Aug 17 '10 at 5:23
source share

Here is the code I was looking for:

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

or

 DDL.SelectedIndex = DDL.Items.IndexOf(DDL.Items.FindByValue("PassedValue")); 
+28
Aug 16 '10 at 20:12
source share

Well, if I understood your question correctly. The solution to set the value for this dropdown is:

 dropdownlist1.Text="Your Value"; 

This will only work if this value exists in the data source of the drop-down list.

+4
May 9, '13 at 4:13
source share

If you need to select a list item based on an expression:

 foreach (ListItem listItem in list.Items) { listItem.Selected = listItem.Value.Contains("some value"); } 
+4
Jan 02 '14 at 23:36
source share
 var index = ctx.Items.FirstOrDefault(item => Equals(item.Value, Settings.Default.Format_Encoding)); ctx.SelectedIndex = ctx.Items.IndexOf(index); 

OR

 foreach (var listItem in ctx.Items) listItem.Selected = Equals(listItem.Value as Encoding, Settings.Default.Format_Encoding); 

This should work ... especially when using advanced RAD controls in which FindByText / Value doesn't even exist!

+1
Dec 17 '14 at 23:30
source share
 ddList.Items.FindByText("oldValue").Selected = false; ddList.Items.FindByText("newValue").Selected = true; 
+1
Dec 21 '16 at 11:10
source share
  ddlemployee.DataSource = ds.Tables[0]; ddlemployee.DataTextField = "Employee Name"; ddlemployee.DataValueField = "RecId"; ddlemployee.DataBind(); ddlemployee.Items.Insert(0, "All"); 
-3
Jul 28 '15 at 20:01
source share



All Articles