I am adding items to combo box using comboBox.Items.Add(entry);. But how can I avoid duplicate entries (i.e same name entries) in combobox. Is there any lib fun
The Items collection has a Contains method
if (!comboBox.Items.Contains(entry)) {
comboBox.Items.Add(entry);
}
The ComboBox.Items property is of type System.Windows.Forms.ComboBox.ObjectCollection, which declares the Contains method like this
public bool Contains(object value)
If you want to use AddRange, you must provide the items in an array. Therefore you must make sure that this array does not contain duplicates. Moreover, if the ComboBox already contains items, you must make sure that this array does not contain the same items.
Let's first assume that the ComboBox is empty and that your items are given by some enumeration (this could be a List<T> or an array for instance):
comboBox.Items.AddRange(
itemsToAdd
.Distinct()
.ToArray()
);
You must have a using System.Linq; at the top of your code. Also you might want to order the items. I assume that they are of string type:
comboBox.Items.AddRange(
itemsToAdd
.Distinct()
.OrderBy(s => s)
.ToArray()
);
If the ComboBox already contains items, you will have to exclude them from the added items
comboBox.Items.AddRange(
itemsToAdd
.Except(comboBox.Items.Cast<string>())
.Distinct()
.OrderBy(s => s)
.ToArray()
);
(Again assuming that itemsToAdd is an enumeration of strings.)
Use an HashSet class to bind the control, how depens from the presentation technology, or use the Distinct method of LINQ to filter duplicates.
Check for the item before adding:
if (!comboBox.Items.Contains(entry))
comboBox.Items.Add(entry);
How about Casting the items to String
var check = comboBox1.Items.Cast<string>().Any(c => c.ToString() == "test");