Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# combobox
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 30-Jun-12 23:18pm
wolfsor564
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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());
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

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[^]
  Permalink  
Comments
Jayanta Chatterjee at 11-Mar-13 8:34am
   
My 5 for Best Solution...
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

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);
  Permalink  
Comments
Jayanta Chatterjee at 11-Mar-13 8:35am
   
My 4 for second Best Solution..

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

  Print Answers RSS
0 BillWoodruff 360
1 Mathew Soji 309
2 Maciej Los 270
3 DamithSL 225
4 Afzaal Ahmad Zeeshan 202
0 OriginalGriff 6,249
1 Sergey Alexandrovich Kryukov 5,853
2 DamithSL 5,183
3 Manas Bhardwaj 4,673
4 Maciej Los 3,865


Advertise | Privacy | Mobile
Web03 | 2.8.1411019.1 | Last Updated 11 Mar 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100