Night Walker
Night Walker

Reputation: 21280

Check for specific value in a combobox

How can I check that a combobox in winforms contains some value?

Is there any way of doing it without iterating through all items?

Upvotes: 12

Views: 45891

Answers (5)

Larry Z
Larry Z

Reputation: 23

Using the accepted answer did not work for me as it always returned false even though a check of the list show the value present. What I use is the FindStringExact method, as recommend by Louis and Amit. In this case its a value entered in the comboBox text box.

var index = comboBox1.FindStringExact(comboBox1.Text)
if(index > -1)
{
    //Success followup code
}

Upvotes: 2

Amit N Thore
Amit N Thore

Reputation: 221

To find exact data from combo box we have to check with FindStringExact

int resultIndex = cbEmployee1.FindStringExact(item.Text);

Upvotes: 2

Adam Garner
Adam Garner

Reputation: 1286

The other answers didn't work for me.

This did:

if (comboBox1.Items.Cast<string>().Any(i => i == position))
{
    // Items contains value
}

Hope this helps!

Upvotes: 2

Louis Waweru
Louis Waweru

Reputation: 3672

int index = comboBox1.FindString("some value"); comboBox1.SelectedIndex = index;

http://msdn.microsoft.com/en-us/library/wxyt1t12.aspx#Y500

There's also FindStringExact http://msdn.microsoft.com/en-us/library/c440x2eb.aspx

Upvotes: 10

Darin Dimitrov
Darin Dimitrov

Reputation: 1039418

if (comboBox1.Items.Contains("some value"))
{

}

If the items are some custom object instead of strings you might need to override the Equals method.

Upvotes: 24

Related Questions