236

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"; 
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

27 Answers27

329

This should do the trick:

Combox1.SelectedIndex = Combox1.FindStringExact("test1")
Norbert B.
  • 5,650
  • 3
  • 25
  • 30
  • Seems a better answer to me because you have a return value you can save temporary in a variable and use it to test wether you have found the value you were looking for. – Áxel Costas Pena May 06 '14 at 12:15
  • what if there are more than one "test1" value in combox1 – thoitbk Jan 04 '15 at 10:31
  • 1
    @thoitbk - According to the MSDN at https://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.findstringexact%28v=vs.110%29.aspx, the method `FindStringExact()` **"Finds the first item in the combo box that matches the specified string."** – dub stylee Jan 22 '15 at 20:30
221

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.

Luke
  • 18,585
  • 24
  • 87
  • 110
Andrew Kennan
  • 13,947
  • 3
  • 24
  • 33
  • 8
    Surely that just sets the text in the editable area of the ComboBox rather than selecting the relevant item from the list? If the list items collection contains objects rather than just strings, then I doubt this would select the appropriate ListItem object, rather it would just set the Text property on the ComboBox? – TabbyCool Jan 05 '10 at 16:28
  • 9
    It does set the SelectedValue property of the control – Henryk Mar 05 '10 at 10:08
  • Nice. Works beautifully for font size, weight, and family pulldowns. No casts or conversions between classes. Soooo much easier! – Lance Cleveland May 08 '11 at 21:48
  • 4
    Just in case : This parameter must be set only after populating the combobox. – Antoine Rodriguez Oct 14 '12 at 18:45
  • there is no .Text in silverlight. – Syaiful Nizam Yahya Jan 10 '13 at 13:05
  • 1
    It does not work when ComboBox .DropDownStyle = ComboBoxStyle.DropDownList; – Jayant Varshney Dec 21 '13 at 07:34
  • I was looking for how to set a combobox, and I thought it would be some convoluted process but this does the trick! – user Mar 06 '14 at 17:12
  • 14
    My combobox dropdownstyle is DropDownList and .Text = "some text" does not work. This solution worked fine for me: Combox1.SelectedIndex = Combox1.FindStringExact("test1") – Mayank Apr 02 '14 at 04:26
  • This solution seems to work for me. Thanks! For good measure I also put in SelectedItem to be the same as Text. – Svein Terje Gaup Sep 15 '21 at 12:15
53

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.

Spence
  • 28,526
  • 15
  • 68
  • 103
  • 1
    Remember its SelectedINDEX not SelectedITEM...And the compiler won't complain, just fail to set the combobox value – Rob Jan 31 '17 at 20:16
  • Don't you love logical errors that don't throw any exception, they just don't work... – Spence Jan 31 '17 at 23:34
  • this is selecting the item, but not calling the onChange event on the combobox – mrid Jan 11 '18 at 11:02
  • `IndexOf` will only throw an exception if you pass it `null`. Merely not finding the item will cause it to return -1 (which conveniently is a valid value for `SelectedIndex`) – Ben Voigt Oct 01 '20 at 22:57
44

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

comboBox1.SelectedItem = "test1";
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Frederik Gheysels
  • 56,135
  • 11
  • 101
  • 154
  • 20
    No it is not: http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selecteditem.aspx – Frederik Gheysels Mar 05 '10 at 10:15
  • 1
    Saved the day! The selected item must match the type - that was it for me! I was scratching my head why the selected item was not set even the item was clearly there - turned out to be a type mismatch! – Sudhanshu Mishra May 15 '15 at 02:43
  • For completeness, useful to have the description from the above link, especially since this answer performs the matching check suggested by other answers including the preferred one from @norbertB: **When you set the SelectedItem property to an object, the ComboBox attempts to make that object the currently selected one in the list.** _If the object is found in the list_, **it is displayed in the edit portion of the ComboBox and the SelectedIndex property is set to the corresponding index. If the object does not exist in the list, the SelectedIndex property is left at its current value.** – DanG Mar 29 '18 at 20:56
17
ComboBox1.SelectedIndex= ComboBox1.FindString("Matching String");

Try this in windows Form.

Muhammad Sohail
  • 828
  • 9
  • 18
14

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;
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
gabore
  • 353
  • 3
  • 11
  • 2
    This worked for me, but you need to be careful that the items in your ComboBox are actually ComboBoxItems as it's possible to put other items in there too. – Grant Sep 30 '13 at 04:10
  • This worked great in WinRT 8.1. I actually wrapped the top foreach in an extension method like dave wrote in his SelectItemByValue() solution, and it was really the perfect solution. – Speednet May 21 '15 at 15:57
10

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);
dave
  • 2,291
  • 3
  • 19
  • 25
10

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");
Brian Rudolph
  • 6,142
  • 2
  • 23
  • 19
  • 1
    comboBox1.Items.IndexOf... risks a NullReferenceException if Items is empty. – Gary Feb 17 '12 at 20:48
  • @Gary: No it doesn't, `Items` will always be an non-null collection, even if there are no items in the collection (`Items.Count == 0`) – Ben Voigt Oct 01 '20 at 22:54
6
comboBox1.SelectedItem.Text = "test1";
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Ben
  • 69
  • 1
  • 1
5

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

comboBox1.SelectedIndex = 0; 
Bo Persson
  • 90,663
  • 31
  • 146
  • 203
ihcarp
  • 105
  • 1
  • 1
  • 5
  • This does not always work... See here: https://stackoverflow.com/questions/12839444/invalidargument-value-of-0-is-not-valid-for-selectedindex-parameter-name-s – JGFMK Jul 05 '19 at 11:44
5

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;
}
taskinoor
  • 45,586
  • 12
  • 116
  • 142
Jelle Smits
  • 59
  • 1
  • 1
5

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!

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Roman Polen.
  • 549
  • 7
  • 10
2

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");
Amit Bhagat
  • 4,182
  • 3
  • 23
  • 24
2
  • 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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user53378
  • 160
  • 4
2

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.

Megacan
  • 2,510
  • 3
  • 20
  • 31
2
_cmbTemplates.SelectedText = "test1"

or maybe

_cmbTemplates.SelectedItem= _cmbTemplates.Items.Equals("test1");
Dean
  • 65
  • 5
2

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

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

gangus
  • 103
  • 1
  • 7
1

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;
        }
Monzur
  • 1,341
  • 14
  • 11
1

this works for me.....

comboBox.DataSource.To<DataTable>().Select(" valueMember = '" + valueToBeSelected + "'")[0]["DislplayMember"];
Jaydeep Karena
  • 159
  • 1
  • 5
  • 14
1

I know this isn't what the OP asked but could it be that they don't know? There are already several answers here so even though this is lengthy I thought it could be useful to the community.

Using an enum to fill a combo box allows for easy use of the SelectedItem method to programmatically select items in the combobox as well as loading and reading from the combobox.

public enum Tests
    {
        Test1,
        Test2,
        Test3,
        None
    }

// Fill up combobox with all the items in the Tests enum
    foreach (var test in Enum.GetNames(typeof(Tests)))
    {
        cmbTests.Items.Add(test);
    }

    // Select combobox item programmatically
    cmbTests.SelectedItem = Tests.None.ToString();

If you double click the combo box you can handle the selected index changed event:

private void cmbTests_SelectedIndexChanged(object sender, EventArgs e)
{
    if (!Enum.TryParse(cmbTests.Text, out Tests theTest))
    {
        MessageBox.Show($"Unable to convert {cmbTests.Text} to a valid member of the Tests enum");
        return;
    }

    switch (theTest)
    {
        case Tests.Test1:
            MessageBox.Show("Running Test 1");
            break;

        case Tests.Test2:
            MessageBox.Show("Running Test 2");
            break;

        case Tests.Test3:
            MessageBox.Show("Running Test 3");
            break;

        case Tests.None:

            // Do nothing

            break;

        default:
            MessageBox.Show($"No support for test {theTest}.  Please add");
            return;
    }
}

You can then run tests from a button click handler event:

 private void btnRunTest1_Click(object sender, EventArgs e)
    {
        cmbTests.SelectedItem = Tests.Test1.ToString();
    }
Grant Johnson
  • 317
  • 3
  • 8
1
  ListItem li = DropDownList.Items.FindByValue("13001");
  DropDownList.SelectedIndex = ddlCostCenter.Items.IndexOf(li);

For your case you can use

DropDownList.Items.FindByText("Text");
Bo Persson
  • 90,663
  • 31
  • 146
  • 203
user874163
  • 27
  • 1
1

if you are binding Datasource via Dataset, then you should use "SelectedValue"

cmbCategoryList.SelectedValue = (int)dsLookUp.Tables[0].Select("WHERE PRODUCTCATEGORYID = 1")[0]["ID"];
Aurora
  • 422
  • 1
  • 7
  • 21
1
combo.Items.FindByValue("1").Selected = true;
Marijn
  • 10,367
  • 5
  • 59
  • 80
Anderson
  • 21
  • 1
-1

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

Nishan
  • 3,644
  • 1
  • 32
  • 41
-2

Please try this way, it works for me:

Combobox1.items[Combobox1.selectedIndex] = "replaced text";
Bo Persson
  • 90,663
  • 31
  • 146
  • 203
  • You should check that selectedIndex is not -1 first, or more precisely that it is >= 0 and < .items.length. – Gary Feb 17 '12 at 20:50
-3

It should work

Yourcomboboxname.setselecteditem("yourstring");

And if you want to set database string use this

Comboboxname.setselecteditem(ps.get string("databasestring"));
Andy K
  • 4,944
  • 10
  • 53
  • 82