Click here to Skip to main content
15,902,823 members
Please Sign up or sign in to vote.
2.09/5 (4 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 7-Dec-21 17:54pm

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:

C#
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());
 
Share this answer
 
Why not just fetch the unique ones from database itself?
Like:
SQL
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[^]
 
Share this answer
 
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

C#
var itemArry= myComboBox.Items.SelectMany(i => i).Distinct().ToArray();
myComboBox.Items.Clear();
myComboBox.Items.AddRange(itemArry);
 
Share this answer
 
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
C#
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
C#
comboBox1.DataSource = list.Select(x => x.Name).Distinct().ToList();
 
Share this answer
 
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