1

I'm having some trouble with something that I'm sure has an easy workaround.

I have different objects from a class which are bind to a combobox.

    MyClass myclassObj = new MyClass();
    bindingSource1.DataSource = myclassObj.myList;
    combobox1.DataSource = bindingSource1;

The problem with this is that my ToString() override prints out a property called "name". Now, my objects sometimes have the same names, but other different properties, which causes my combobox to appear to have duplicates (although they're different objects).

My question is, is there a way to hide these duplicate names?

gemathus
  • 108
  • 9
  • 3
    I would add another property to MyClass that returns a list of the objects without duplicates – Steve Aug 10 '16 at 16:04
  • 1
    While the display strings are duplicate, but those are distinct objects. You should not hide those duplicates, instead you should change the display string to show a suitable value. If you remove duplicates, some of objects in your reference list will not be selectable through combo box. – Reza Aghaei Aug 10 '16 at 16:04
  • There are a ton of questions dealing with this. This is probably most relevant: http://stackoverflow.com/questions/12757138/remove-duplicates-from-combobox-which-is-bind-to-dataset Or this: http://stackoverflow.com/questions/4753768/distinct-values-in-data-bound-combobox – RIanGillis Aug 10 '16 at 16:07
  • @RezaAghaei How exactly would yo go about changing the display string? I tried .DisplayMember but got nowhere. – gemathus Aug 10 '16 at 16:40
  • 1
    You should change the `ToString` method, or add another property for example `DisplayText` which returns for example `string.Format("{0} ({1})", Name, Id);` This way, the displayed strings will be unique. – Reza Aghaei Aug 10 '16 at 16:42
  • 2
    It's better to include codes of your classes in question. – Reza Aghaei Aug 10 '16 at 16:45

1 Answers1

0

you can remove duplicate value directly from the list or use below code to remove duplicate value from the combobox, concept is same as i told get distinct value from combobox, clear combobox and re-assign it with distinct value example code are as per below

MyClass myclassObj = new MyClass();
bindingSource1.DataSource = myclassObj.myList;
combobox1.DataSource = bindingSource1;

//just add below three line 
var itemArry= combobox1.Items.SelectMany(i => i).Distinct().ToArray();
combobox1.Items.Clear();
combobox1.Items.AddRange(itemArry);