How to SELECT a dropdown list item by value progra

2019-01-21 10:17发布

How to SELECT a drop down list item by value programatically in C#.NET?

10条回答
▲ chillily
2楼-- · 2019-01-21 10:57

If you know that the dropdownlist contains the value you're looking to select, use:

ddl.SelectedValue = "2";

If you're not sure if the value exists, use (or you'll get a null reference exception):

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

if (selectedListItem != null)
{
    selectedListItem.Selected = true;
}
查看更多
淡お忘
3楼-- · 2019-01-21 11:05

For those who come here by search (because this thread is over 3 years old):

string entry // replace with search value

if (comboBox.Items.Contains(entry))
   comboBox.SelectedIndex = comboBox.Items.IndexOf(entry);
else
   comboBox.SelectedIndex = 0;
查看更多
劫难
4楼-- · 2019-01-21 11:05
再贱就再见
5楼-- · 2019-01-21 11:05

ddlPageSize.Items.FindByValue("25").Selected = true;

查看更多
做个烂人
6楼-- · 2019-01-21 11:08
myDropDown.SelectedIndex = 
    myDropDown.Items.IndexOf(myDropDown.Items.FindByValue("myValue"))
查看更多
何必那么认真
7楼-- · 2019-01-21 11:09
ddl.SetSelectedValue("2");

With a handy extension:

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: Any code is released into the public domain. No attribution required.

查看更多
登录 后发表回答