[c#] How to SELECT a dropdown list item by value programmatically

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

This question is related to c# .net drop-down-menu

The answer is


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.


combobox1.SelectedValue = x;

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


Please try below:

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

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;

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

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


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


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

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.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface How to implement drop down list in flutter? How can I create a dropdown menu from a List in Tkinter? How can I close a dropdown on click outside? Making a drop down list using swift? HTML: Select multiple as dropdown How to get selected value of a dropdown menu in ReactJS Avoid dropdown menu close on click inside Bootstrap 3 dropdown select How to make a drop down list in yii2? Android custom dropdown/popup menu