listbox items not displaying properly

后端 未结 2 751
青春惊慌失措
青春惊慌失措 2021-01-28 03:24

I have a listbox and a ListItem object which I am adding to the listbox so that I can retrieve a value from the selected item which is different then the displayed member.

2条回答
  •  别那么骄傲
    2021-01-28 04:04

    From MSDN:

    When an object is being added to the ListBox, the control uses the text defined in the ToString method of the object unless a member name within the object is specified in the DisplayMember property.

    ListBox will convert item to string calling ToString(). In your case you just need to change your ListItem class like this:

    class ListItem
    {
        public string DisplayMember;
        public string ValueMember;
    
        public ListItem(string n,string v) {
             DisplayMember = n;
             ValueMember = v;
        }
    
        public override string ToString() {
            return DisplayMember;
        }
    }
    

    As alternative you can se the DisplayMember property (in designer or with code) to use your property (you called that property DisplayMember but its name is free because it must be specified and it doesn't use any convention):

    listBox1.DisplayMember = "DisplayMember";
    

提交回复
热议问题