listbox items not displaying properly

后端 未结 2 752
青春惊慌失措
青春惊慌失措 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 03:56

    try this it should work for you!

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

    }

    public CompareTimeFramesForm()
    {
        InitializeComponent();           
        listBox1.Items.Add(new ListItem("# of Bookings", null).DisplayMember);
        listBox1.Items.Add(new ListItem("People", "guaranteed_count").DisplayMember);
    }
    
    0 讨论(0)
  • 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";
    
    0 讨论(0)
提交回复
热议问题