Reputation: 6471
I have this:
<ComboBox SelectedValuePath="Content" x:Name="cb">
<ComboBoxItem>Combo</ComboBoxItem>
<ComboBoxItem>Box</ComboBoxItem>
<ComboBoxItem>Item</ComboBoxItem>
</ComboBox>
If I use
cb.Items.Contains("Combo")
or
cb.Items.Contains(new ComboBoxItem {Content = "Combo"})
it returns False
.
Can anyone tell me how do I check if a ComboBoxItem
named Combo
exists in the ComboBox
cb
?
Upvotes: 11
Views: 48064
Reputation: 41
In C# Winform Apps You can do the following:
//Create a function like below
internal static bool CheckCombo(ComboBox.ObjectCollection items, string Search)
{
bool isFound = false;
foreach (var item in items)
{
if (item.Equals(Search))
{
isFound = true; break;
}
}
return isFound;
}
You can call the function like this when adding your items to the combo box
if (!Functions.CheckCombo(Combobox.Items, "ValueToSearch"))
{
//Adding the value if is not found in the combobox
Combobox.Items.Add("ValueToSearch");
}
Upvotes: 0
Reputation: 81243
Items is an ItemCollection
and not list of strings
. In your case its a collection of ComboboxItem
and you need to check its Content
property.
cb.Items.Cast<ComboBoxItem>().Any(cbi => cbi.Content.Equals("Combo"));
OR
cb.Items.OfType<ComboBoxItem>().Any(cbi => cbi.Content.Equals("Combo"));
You can loop over each item and break in case you found desired item -
bool itemExists = false;
foreach (ComboBoxItem cbi in cb.Items)
{
itemExists = cbi.Content.Equals("Combo");
if (itemExists) break;
}
Upvotes: 16
Reputation: 2357
If you want to use the Contains
function as in cb.Items.Contains("Combo")
you have to add strings to your ComboBox, not ComboBoxItems: cb.Items.Add("Combo")
. The string will display just like a ComboBoxItem.
Upvotes: 6