47

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

4
  • are looking for a way to do this using automation (say for testing)? Commented Aug 8, 2009 at 17:18
  • 1
    Is this for WinForms, WPF, web? Commented Aug 8, 2009 at 17:23
  • No Im just to select the country by value depending the value I have in the DB Commented Aug 8, 2009 at 17:28
  • Possible duplicate of Setting dropdownlist selecteditem programmatically Commented Jan 16, 2017 at 7:34

10 Answers 10

86

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

here is same 2nd solution but in one line of code: ddl.Items.FindByValue("2").Selected=true ;
The dropdownlist is in a popup which has been populated on page load. I am trying to set the selected index before showing the popup but it is not working. Can you please help? stackoverflow.com/questions/28883433/…
26

Please try below:

myDropDown.SelectedIndex = 
myDropDown.Items.IndexOf(myDropDown.Items.FindByValue("myValue"))

3 Comments

The value is becoming -1 in the myDropDown.SelectedIndex why?
probably because myDropDown.Items haven't an item "myValue"
IndexOf() returns -1 if the item isn't in the collection. FindByValue() isn't finding the item you're looking for. Just break it apart into separate statements if you need to debug it.
6
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.

Comments

2

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

Comments

2

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

1 Comment

This was already posted multiple times. Anything new you'd like to add?
1
combobox1.SelectedValue = x;

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

2 Comments

You can't because the Selected value only gets the value not set
David - you are actually incorrect. Give it a try, and if you gave the -1, you should probably remove it! You will of course get an exception if the value doesn't exist, but it otherwise works just fine.
1

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.

2 Comments

@MarioDS Really? Isn't more or less indicative of being different. Does it work or not? Is it the same as something provided or not? If yes to first and no to second, why the minus?
@MarioDS The answer provides the same function with less code. All answers on here provide different ways for different benefits, benefits of this one is less code.
1

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");

Comments

0

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;

1 Comment

The Contains method takes a ListItem parameter, not a string value parameter.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.