如何以编程方式按值select下拉列表项目

如何在C#.NET中通过编程方式select一个下拉列表项?

如果您知道下拉列表中包含您要select的值,请使用:

ddl.SelectedValue = "2"; 

如果您不确定该值是否存在,请使用(或者您将得到一个空引用exception):

 ListItem selectedListItem = ddl.Items.FindByValue("2"); if (selectedListItem != null) { selectedListItem.Selected = true; } 
 myDropDown.SelectedIndex = myDropDown.Items.IndexOf(myDropDown.Items.FindByValue("myValue")) 
 ddl.SetSelectedValue("2"); 

有一个方便的扩展:

 public static class WebExtensions { /// <summary> /// Selects the item in the list control that contains the specified value, if it exists. /// </summary> /// <param name="dropDownList"></param> /// <param name="selectedValue">The value of the item in the list control to select</param> /// <returns>Returns true if the value exists in the list control, false otherwise</returns> public static Boolean SetSelectedValue(this DropDownList dropDownList, String selectedValue) { ListItem selectedListItem = dropDownList.Items.FindByValue(selectedValue); if (selectedListItem != null) { selectedListItem.Selected = true; return true; } else return false; } } 

注意 :任何代码都被释放到公共领域。 不需要归属

 combobox1.SelectedValue = x; 

我怀疑你可能想哟听到别的,但这是你要求的。

这是一个简单的方法,从基于stringval的下拉列表中select一个选项

 private void SetDDLs(DropDownList d,string val) { ListItem li; for (int i = 0; i < d.Items.Count; i++) { li = d.Items[i]; if (li.Value == val) { d.SelectedIndex = i; break; } } } 

伊恩博伊德(上面)有一个很好的答案 – 添加到伊恩·博伊德的类“WebExtensions”在下拉列表中select一个项目基于文本:

  /// <summary> /// Selects the item in the list control that contains the specified text, if it exists. /// </summary> /// <param name="dropDownList"></param> /// <param name="selectedText">The text of the item in the list control to select</param> /// <returns>Returns true if the value exists in the list control, false otherwise</returns> public static Boolean SetSelectedText(this DropDownList dropDownList, String selectedText) { ListItem selectedListItem = dropDownList.Items.FindByText(selectedText); if (selectedListItem != null) { selectedListItem.Selected = true; return true; } else return false; } 

调用它:

 WebExtensions.SetSelectedText(MyDropDownList, "MyValue"); 

对于那些通过search来到这里(因为这个线程超过3岁):

 string entry // replace with search value if (comboBox.Items.Contains(entry)) comboBox.SelectedIndex = comboBox.Items.IndexOf(entry); else comboBox.SelectedIndex = 0; 

看看这篇文章

如何通过值Asp.Net在DropDownList中select一个项目

我更喜欢

 if(ddl.Items.FindByValue(string) != null) { ddl.Items.FindByValue(string).Selected = true; } 

将ddlreplace为您的stringvariables名称或值的下拉列表ID和string。