如何以编程方式按值选择下拉列表项

Dav*_*ici 43 .net c# drop-down-menu

如何在C#.NET中以编程方式按值选择下拉列表项?

Sco*_*ttE 81

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

ddl.SelectedValue = "2";
Run Code Online (Sandbox Code Playgroud)

如果您不确定该值是否存在,请使用(或者您将获得空引用异常):

ListItem selectedListItem = ddl.Items.FindByValue("2");

if (selectedListItem != null)
{
    selectedListItem.Selected = true;
}
Run Code Online (Sandbox Code Playgroud)

  • 这里是相同的第二个解决方案,但在一行代码中:ddl.Items.FindByValue("2").Selected = true; (3认同)
  • 如果找不到该项,将导致错误. (3认同)

wom*_*omp 24

请尝试以下:

myDropDown.SelectedIndex = 
myDropDown.Items.IndexOf(myDropDown.Items.FindByValue("myValue"))
Run Code Online (Sandbox Code Playgroud)


Ian*_*oyd 6

ddl.SetSelectedValue("2");
Run Code Online (Sandbox Code Playgroud)

方便的扩展:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:任何代码都将发布到公共域中.无需归属.