How to SELECT a dropdown list item by value programmatically

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

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

相关标签:
10条回答
  • 2020-12-13 00:43

    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;
                }
            }
        }
    
    0 讨论(0)
  • 2020-12-13 00:46

    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;
    
    0 讨论(0)
  • 2020-12-13 00:47

    Please try below:

    myDropDown.SelectedIndex = 
    myDropDown.Items.IndexOf(myDropDown.Items.FindByValue("myValue"))
    
    0 讨论(0)
  • 2020-12-13 00:49

    If anyone else is trying this and facing problem then let me point one possible problem: If you are using Web Application then inside Page_Load if you are loading drop-down from DB and at the sametime you want to load data, then first load your drop-down lists and then load your data with selected drop-down conditions.

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            LoadDropdown(); //drop-downs generated first
            LoadData(); // other data loading and drop-down value selection logic here
        }
    }
    

    And for successfully selecting drop-down from code follow the approved answer above which is

    ddl.SelectedValue = "2";.

    Hope it solves the problem

    0 讨论(0)
提交回复
热议问题