Reputation: 21280
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
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
Reputation: 221
To find exact data from combo box we have to check with FindStringExact
int resultIndex = cbEmployee1.FindStringExact(item.Text);
Upvotes: 2
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
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
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