How to SELECT a dropdown list item by value programmatically

前端 未结 10 574
滥情空心
滥情空心 2020-12-13 00:11

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

10条回答
  •  悲哀的现实
    2020-12-13 00:32

    Ian Boyd (above) had a great answer -- Add this to Ian Boyd's class "WebExtensions" to select an item in a dropdownlist based on text:

    /// 
    /// Selects the item in the list control that contains the specified text, if it exists.
    /// 
    /// 
    /// The text of the item in the list control to select
    /// Returns true if the value exists in the list control, false otherwise
    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;
    }
    

    To call it:

    WebExtensions.SetSelectedText(MyDropDownList, "MyValue");
    

提交回复
热议问题