user1903439
user1903439

Reputation: 2001

Combo boxes duplicate entries

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 function

Upvotes: 4

Views: 12893

Answers (4)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112299

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.)

Upvotes: 4

spajce
spajce

Reputation: 7082

How about Casting the items to String

var check = comboBox1.Items.Cast<string>().Any(c => c.ToString() == "test");

Upvotes: 0

Matteo Migliore
Matteo Migliore

Reputation: 923

Use an HashSet class to bind the control, how depens from the presentation technology, or use the Distinct method of LINQ to filter duplicates.

Upvotes: 1

Moha Dehghan
Moha Dehghan

Reputation: 18443

Check for the item before adding:

if (!comboBox.Items.Contains(entry))
    comboBox.Items.Add(entry);

Upvotes: 13

Related Questions