如何在C#.NET中编程选择下拉列表项?
发布于 2009-08-08 17:44:09
如果您知道dropdownlist包含要选择的值,请使用:
ddl.SelectedValue = "2";如果你不确定这个值是否存在,使用(否则你会得到一个空引用异常):
ListItem selectedListItem = ddl.Items.FindByValue("2");
if (selectedListItem != null)
{
selectedListItem.Selected = true;
}发布于 2009-08-08 17:23:01
请在下面尝试:
myDropDown.SelectedIndex =
myDropDown.Items.IndexOf(myDropDown.Items.FindByValue("myValue"))发布于 2012-06-29 05:14:07
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;
}
}Note:任何代码都会发布到公共领域。不需要属性。
https://stackoverflow.com/questions/1249394
复制相似问题