[c#] How do I set the selected item in a comboBox to match my string using C#?

I have a string "test1" and my comboBox contains test1, test2, and test3. How do I set the selected item to "test1"? That is, how do I match my string to one of the comboBox items?

I was thinking of the line below, but this doesn't work.

comboBox1.SelectedText = "test1"; 

This question is related to c# winforms combobox

The answer is


If the items in your ComboBox are strings, you can try:

comboBox1.SelectedItem = "test1";

  ListItem li = DropDownList.Items.FindByValue("13001");
  DropDownList.SelectedIndex = ddlCostCenter.Items.IndexOf(li);

For your case you can use

DropDownList.Items.FindByText("Text");

All methods, tricks, and lines of code setting ComboBox item will not work until the ComboBox has a parent.


Have you tried the Text property? It works for me.

ComboBox1.Text = "test1";

The SelectedText property is for the selected portion of the editable text in the textbox part of the combo box.


Assuming that your combobox isn't databound you would need to find the object's index in the "items" collection on your form and then set the "selectedindex" property to the appropriate index.

comboBox1.SelectedIndex = comboBox1.Items.IndexOf("test1");

Keep in mind that the IndexOf function may throw an argumentexception if the item isn't found.


ComboBox1.SelectedIndex= ComboBox1.FindString("Matching String");

Try this in windows Form.


This should do the trick:

Combox1.SelectedIndex = Combox1.FindStringExact("test1")

Assuming that your combobox isn't databound you would need to find the object's index in the "items" collection on your form and then set the "selectedindex" property to the appropriate index.

comboBox1.SelectedIndex = comboBox1.Items.IndexOf("test1");

Keep in mind that the IndexOf function may throw an argumentexception if the item isn't found.


You can say comboBox1.Text = comboBox1.Items[0].ToString();


You don't have that property in the ComboBox. You have SelectedItem or SelectedIndex. If you have the objects you used to fill the combo box then you can use SelectedItem.

If not you can get the collection of items (property Items) and iterate that until you get the value you want and use that with the other properties.

hope it helps.


I have created a Function which will return the Index of the Value

        public static int SelectByValue(ComboBox comboBox, string value)
        {
            int i = 0;
            for (i = 0; i <= comboBox.Items.Count - 1; i++)
            {
                DataRowView cb;
                cb = (DataRowView)comboBox.Items[i];
                if (cb.Row.ItemArray[0].ToString() == value)// Change the 0 index if your want to Select by Text as 1 Index
                {
                    return i;
                }
            }
            return -1;
        }

For me this worked only:

foreach (ComboBoxItem cbi in someComboBox.Items)
{
    if (cbi.Content as String == "sometextIntheComboBox")
    {
        someComboBox.SelectedItem = cbi;
        break;
    }
}

MOD: and if You have your own objects as items set up in the combobox, then substitute the ComboBoxItem with one of them like:

foreach (Debitor d in debitorCombo.Items)
{
    if (d.Name == "Chuck Norris")
    {
        debitorCombo.SelectedItem = d;
        break;
    }
}

Assuming that your combobox isn't databound you would need to find the object's index in the "items" collection on your form and then set the "selectedindex" property to the appropriate index.

comboBox1.SelectedIndex = comboBox1.Items.IndexOf("test1");

Keep in mind that the IndexOf function may throw an argumentexception if the item isn't found.


ComboBox1.SelectedIndex= ComboBox1.FindString("Matching String");

Try this in windows Form.


This should do the trick:

Combox1.SelectedIndex = Combox1.FindStringExact("test1")

If the items in your ComboBox are strings, you can try:

comboBox1.SelectedItem = "test1";

SelectedText is to get or set the actual text in the string editor for the selected item in the combobox as documented here . This goes uneditable if you set:

comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;

Use:

comboBox1.SelectedItem = "test1";

or:

comboBox1.SelectedIndex = comboBox1.Items.IndexOf("test1");

Supposing test1, test2, test3 belong to comboBox1 collection following statement will work.

comboBox1.SelectedIndex = 0; 

You don't have that property in the ComboBox. You have SelectedItem or SelectedIndex. If you have the objects you used to fill the combo box then you can use SelectedItem.

If not you can get the collection of items (property Items) and iterate that until you get the value you want and use that with the other properties.

hope it helps.


It should work

Yourcomboboxname.setselecteditem("yourstring");

And if you want to set database string use this

Comboboxname.setselecteditem(ps.get string("databasestring"));

All methods, tricks, and lines of code setting ComboBox item will not work until the ComboBox has a parent.


I've used an extension method:

public static void SelectItemByValue(this ComboBox cbo, string value)
{
    for(int i=0; i < cbo.Items.Count; i++)
    {
        var prop = cbo.Items[i].GetType().GetProperty(cbo.ValueMember);
        if (prop!=null && prop.GetValue(cbo.Items[i], null).ToString() == value)
        {
             cbo.SelectedIndex = i;
             break;
        }
    } 
}

Then just consume the method:

ddl.SelectItemByValue(value);

comboBox1.SelectedItem.Text = "test1";

  ListItem li = DropDownList.Items.FindByValue("13001");
  DropDownList.SelectedIndex = ddlCostCenter.Items.IndexOf(li);

For your case you can use

DropDownList.Items.FindByText("Text");

combo.Items.FindByValue("1").Selected = true;

this works for me.....

comboBox.DataSource.To<DataTable>().Select(" valueMember = '" + valueToBeSelected + "'")[0]["DislplayMember"];

If the items in your ComboBox are strings, you can try:

comboBox1.SelectedItem = "test1";

Supposing test1, test2, test3 belong to comboBox1 collection following statement will work.

comboBox1.SelectedIndex = 0; 

_cmbTemplates.SelectedText = "test1"

or maybe

_cmbTemplates.SelectedItem= _cmbTemplates.Items.Equals("test1");

You can say comboBox1.Text = comboBox1.Items[0].ToString();


I've used an extension method:

public static void SelectItemByValue(this ComboBox cbo, string value)
{
    for(int i=0; i < cbo.Items.Count; i++)
    {
        var prop = cbo.Items[i].GetType().GetProperty(cbo.ValueMember);
        if (prop!=null && prop.GetValue(cbo.Items[i], null).ToString() == value)
        {
             cbo.SelectedIndex = i;
             break;
        }
    } 
}

Then just consume the method:

ddl.SelectItemByValue(value);

_cmbTemplates.SelectedText = "test1"

or maybe

_cmbTemplates.SelectedItem= _cmbTemplates.Items.Equals("test1");

this works for me.....

comboBox.DataSource.To<DataTable>().Select(" valueMember = '" + valueToBeSelected + "'")[0]["DislplayMember"];

If the items in your ComboBox are strings, you can try:

comboBox1.SelectedItem = "test1";

_cmbTemplates.SelectedText = "test1"

or maybe

_cmbTemplates.SelectedItem= _cmbTemplates.Items.Equals("test1");

This solution is based on MSDN with some modifications I made.

  • It finds exact or PART of string and sets it.

    private int lastMatch = 0;
    private void textBoxSearch_TextChanged(object sender, EventArgs e)
    {
        // Set our intial index variable to -1.
        int x = 0;
        string match = textBoxSearch.Text;
        // If the search string is empty set to begining of textBox
        if (textBoxSearch.Text.Length != 0)
        {
            bool found = true;
            while (found)
            {
                if (comboBoxSelect.Items.Count == x)
                {
                    comboBoxSelect.SelectedIndex = lastMatch;
                    found = false;
                }
                else
                {
                    comboBoxSelect.SelectedIndex = x;
                    match = comboBoxSelect.SelectedValue.ToString();
                    if (match.Contains(textBoxSearch.Text))
                    {
                        lastMatch = x;
                        found = false;
                    }
                    x++;
                }
            }
        }
        else
            comboBoxSelect.SelectedIndex = 0;
    }
    

I hope I helped!


I used KeyValuePair for ComboBox data bind and I wanted to find item by value so this worked in my case:

comboBox.SelectedItem = comboBox.Items.Cast<KeyValuePair<string,string>>().First(item=> item.Value == "value to match");

Have you tried the Text property? It works for me.

ComboBox1.Text = "test1";

The SelectedText property is for the selected portion of the editable text in the textbox part of the combo box.


I have created a Function which will return the Index of the Value

        public static int SelectByValue(ComboBox comboBox, string value)
        {
            int i = 0;
            for (i = 0; i <= comboBox.Items.Count - 1; i++)
            {
                DataRowView cb;
                cb = (DataRowView)comboBox.Items[i];
                if (cb.Row.ItemArray[0].ToString() == value)// Change the 0 index if your want to Select by Text as 1 Index
                {
                    return i;
                }
            }
            return -1;
        }

I've filled my ComboBox with een DataTable filled from a database. Then I've set the DisplayMember and the ValueMember. And I use this code to set the selected item.

foreach (DataRowView Row in ComboBox1.Items)
{
    if (Row["ColumnName"].ToString() == "Value") ComboBox1.SelectedItem = Row;
}

Supposing test1, test2, test3 belong to comboBox1 collection following statement will work.

comboBox1.SelectedIndex = 0; 

Find mySecondObject (of type MyObject) in combobox (containing a list of MyObjects) and select the item:

foreach (MyObject item in comboBox.Items)
{
   if (item.NameOrID == mySecondObject.NameOrID)
    {
        comboBox.SelectedItem = item;
        break;
    }
}

SelectedText is to get or set the actual text in the string editor for the selected item in the combobox as documented here . This goes uneditable if you set:

comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;

Use:

comboBox1.SelectedItem = "test1";

or:

comboBox1.SelectedIndex = comboBox1.Items.IndexOf("test1");

Have you tried the Text property? It works for me.

ComboBox1.Text = "test1";

The SelectedText property is for the selected portion of the editable text in the textbox part of the combo box.


Assuming that your combobox isn't databound you would need to find the object's index in the "items" collection on your form and then set the "selectedindex" property to the appropriate index.

comboBox1.SelectedIndex = comboBox1.Items.IndexOf("test1");

Keep in mind that the IndexOf function may throw an argumentexception if the item isn't found.


I used KeyValuePair for ComboBox data bind and I wanted to find item by value so this worked in my case:

comboBox.SelectedItem = comboBox.Items.Cast<KeyValuePair<string,string>>().First(item=> item.Value == "value to match");

It should work

Yourcomboboxname.setselecteditem("yourstring");

And if you want to set database string use this

Comboboxname.setselecteditem(ps.get string("databasestring"));

For me this worked only:

foreach (ComboBoxItem cbi in someComboBox.Items)
{
    if (cbi.Content as String == "sometextIntheComboBox")
    {
        someComboBox.SelectedItem = cbi;
        break;
    }
}

MOD: and if You have your own objects as items set up in the combobox, then substitute the ComboBoxItem with one of them like:

foreach (Debitor d in debitorCombo.Items)
{
    if (d.Name == "Chuck Norris")
    {
        debitorCombo.SelectedItem = d;
        break;
    }
}

Please try this way, it works for me:

Combobox1.items[Combobox1.selectedIndex] = "replaced text";

This solution is based on MSDN with some modifications I made.

  • It finds exact or PART of string and sets it.

    private int lastMatch = 0;
    private void textBoxSearch_TextChanged(object sender, EventArgs e)
    {
        // Set our intial index variable to -1.
        int x = 0;
        string match = textBoxSearch.Text;
        // If the search string is empty set to begining of textBox
        if (textBoxSearch.Text.Length != 0)
        {
            bool found = true;
            while (found)
            {
                if (comboBoxSelect.Items.Count == x)
                {
                    comboBoxSelect.SelectedIndex = lastMatch;
                    found = false;
                }
                else
                {
                    comboBoxSelect.SelectedIndex = x;
                    match = comboBoxSelect.SelectedValue.ToString();
                    if (match.Contains(textBoxSearch.Text))
                    {
                        lastMatch = x;
                        found = false;
                    }
                    x++;
                }
            }
        }
        else
            comboBoxSelect.SelectedIndex = 0;
    }
    

I hope I helped!


You don't have that property in the ComboBox. You have SelectedItem or SelectedIndex. If you have the objects you used to fill the combo box then you can use SelectedItem.

If not you can get the collection of items (property Items) and iterate that until you get the value you want and use that with the other properties.

hope it helps.


  • Enumerate ListItems in combobox
  • Get equal ones listindex set combobox
  • Set listindex to the found one.

But if I see such a code as a code reviewer, I would recommend to reconsider all the method algorithm.


Have you tried the Text property? It works for me.

ComboBox1.Text = "test1";

The SelectedText property is for the selected portion of the editable text in the textbox part of the combo box.


_cmbTemplates.SelectedText = "test1"

or maybe

_cmbTemplates.SelectedItem= _cmbTemplates.Items.Equals("test1");

SelectedText is to get or set the actual text in the string editor for the selected item in the combobox as documented here . This goes uneditable if you set:

comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;

Use:

comboBox1.SelectedItem = "test1";

or:

comboBox1.SelectedIndex = comboBox1.Items.IndexOf("test1");

You don't have that property in the ComboBox. You have SelectedItem or SelectedIndex. If you have the objects you used to fill the combo box then you can use SelectedItem.

If not you can get the collection of items (property Items) and iterate that until you get the value you want and use that with the other properties.

hope it helps.


This should do the trick:

Combox1.SelectedIndex = Combox1.FindStringExact("test1")

Supposing test1, test2, test3 belong to comboBox1 collection following statement will work.

comboBox1.SelectedIndex = 0; 

combo.Items.FindByValue("1").Selected = true;

Find mySecondObject (of type MyObject) in combobox (containing a list of MyObjects) and select the item:

foreach (MyObject item in comboBox.Items)
{
   if (item.NameOrID == mySecondObject.NameOrID)
    {
        comboBox.SelectedItem = item;
        break;
    }
}

I've filled my ComboBox with een DataTable filled from a database. Then I've set the DisplayMember and the ValueMember. And I use this code to set the selected item.

foreach (DataRowView Row in ComboBox1.Items)
{
    if (Row["ColumnName"].ToString() == "Value") ComboBox1.SelectedItem = Row;
}

Please try this way, it works for me:

Combobox1.items[Combobox1.selectedIndex] = "replaced text";

  • Enumerate ListItems in combobox
  • Get equal ones listindex set combobox
  • Set listindex to the found one.

But if I see such a code as a code reviewer, I would recommend to reconsider all the method algorithm.


SelectedText is to get or set the actual text in the string editor for the selected item in the combobox as documented here . This goes uneditable if you set:

comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;

Use:

comboBox1.SelectedItem = "test1";

or:

comboBox1.SelectedIndex = comboBox1.Items.IndexOf("test1");

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 winforms

How to set combobox default value? Get the cell value of a GridView row Getting the first and last day of a month, using a given DateTime object Check if a record exists in the database Delete a row in DataGridView Control in VB.NET How to make picturebox transparent? Set default format of datetimepicker as dd-MM-yyyy Changing datagridview cell color based on condition C# Inserting Data from a form into an access Database How to use ConfigurationManager

Examples related to combobox

How to set combobox default value? PHP code to get selected text of a combo box How to add items to a combobox in a form in excel VBA? How add items(Text & Value) to ComboBox & read them in SelectedIndexChanged (SelectedValue = null) Get Selected value of a Combobox jQuery "on create" event for dynamically-created elements How to get the selected item of a combo box to a string variable in c# HTML combo box with option to type an entry twitter bootstrap autocomplete dropdown / combobox with Knockoutjs C# winforms combobox dynamic autocomplete