Click here to Skip to main content
14,732,620 members
Please Sign up or sign in to vote.
1.80/5 (3 votes)
See more:
I have populated the combo box with data from a database and I wanted to remove the duplicate names from the combo box items list. Can you give me a code to do it?
Posted
Updated 5-Jun-20 4:55am

It's not necessarily as simple as that - it depends to an extent on what type of items you have filled your ComboBox with. Because you can't just set the Items array (it exposes no public setter, just the getter) you have to create a new array of items, remove the duplicates, and set it back into the ComboBox:

List<object> list = new List<object>();
foreach (object o in myComboBox.Items)
    {
    if (!list.Contains(o))
        {
        list.Add(o);
        }
    }
myComboBox.Items.Clear();
myComboBox.Items.AddRange(list.ToArray());
   
Why not just fetch the unique ones from database itself?
Like:
SELECT DISTINCT Names FROM MstNames


If you still want to, before assigning the datasource, filter the datatable to be used.
To know more of it, read here: MSDN: DataView.RowFilter Property[^]
   
Comments
JayantaChatterjee 11-Mar-13 8:34am
   
My 5 for Best Solution...
As Sandeep's answer best way is select distinct when you select from database.

if you are using c# 3.0 or later you can try below code

var itemArry= myComboBox.Items.SelectMany(i => i).Distinct().ToArray();
myComboBox.Items.Clear();
myComboBox.Items.AddRange(itemArry);
   
Comments
JayantaChatterjee 11-Mar-13 8:35am
   
My 4 for second Best Solution..
Linq:
It own has the property of Distinct()

//Some data in Linq
List<data> list = new List<data>()
{
    Name ="Swaraj Ambekar",
    Name ="Swaraj Ambekar",
    Name ="Swaraj Ambekar",
    Name = "Forbes Technosys"
};

//Adding data source to combobox with linq
comboBox1.DataSource = list.Select(x => x.Name).Distinct().ToList();
   
v3
Comments
CHill60 5-Jun-20 10:10am
   
Solution 3 uses Linq, specifically Distinct() - you haven't really added anything new to this 8 year old thread

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900