问题
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?
回答1:
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;
}
Hope helps,
回答2:
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.
回答3:
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
来源:https://stackoverflow.com/questions/38192443/set-combobox-to-custom-display-format