Set comboBox to custom display format

风流意气都作罢 提交于 2019-12-12 18:13:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!