derekantrican
derekantrican

Reputation: 2275

Set comboBox to custom display format

I've got a WinForms comboBox that contains a list of "Regions" (a custom class I've set up). Each Region has properties Name, Abbreviation, etc. I know I can set the comboBox to comboBox.DisplayMember = "Name";, but I want the display formatting to be "(" + Abbreviation + ") " + Name (e.g. (OR) Oregon).

I know I could create a separate property for this (e.g. DisplayName) and just set the comboBox.DisplayMember = "DisplayName"; but is there another way to do it? Something like comboBox.DisplayMember = "(" + Abbreviation + ") " + Name; or whatever?

Upvotes: 4

Views: 8403

Answers (3)

Berkay Yaylacı
Berkay Yaylacı

Reputation: 4513

You can use combobox's Format event.

 private void comboBox1_Format(object sender, ListControlConvertEventArgs e)
    {
        string Name = ((yourClass)e.ListItem).Property1;
        string LastName = ((yourClass)e.ListItem).Property2;
        e.Value = Name + " " + LastName;
    }

Upvotes: 13

Stefano d'Antonio
Stefano d'Antonio

Reputation: 6152

This is quite old, but I struggled to find why the Format event was not fired.

You also need to set ComboBox.FormattingEnabled to true in order to get the event invoked and used.

Upvotes: 9

Aimnox
Aimnox

Reputation: 899

Another way is to modify the ´ToString()´ method of your class.

If you do that you will change the way the class is isualized everywhere (Comboboxes, listboxes, etc)

public override string ToString()
{
   return "(" + Abbreviation + ") " + Name;
}

It's useless if you want a diferent visualitzation for diferent places, but perfect if you want it always to be the same

Upvotes: 2

Related Questions