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条回答
Bombasti
2楼-- · 2019-01-21 11:09

This is a simple way to select an option from a dropdownlist based on a string val

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;
            }
        }
    }
查看更多
甜甜的少女心
3楼-- · 2019-01-21 11:16

I prefer

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

Replace ddl with the dropdownlist ID and string with your string variable name or value.

查看更多
混吃等死
4楼-- · 2019-01-21 11:24
combobox1.SelectedValue = x;

I suspect you may want yo hear something else, but this is what you asked for.

查看更多
ゆ 、 Hurt°
5楼-- · 2019-01-21 11:24

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:

    /// <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;
    }

To call it:

WebExtensions.SetSelectedText(MyDropDownList, "MyValue");
查看更多
登录 后发表回答