c# add object to listbox and show string of object in it

后端 未结 4 1829
情歌与酒
情歌与酒 2020-12-09 08:51

I\'m using a ListBox and adding objects to it.

The object contains 2 variables, let\'s say username and userid.

How can I add the objects in the list (like l

4条回答
  •  北海茫月
    2020-12-09 09:41

    You can use the DisplayMember and ValueMember properties to display the UserName property of your object and use its UserId property as the list item value:

    class YourItem
    {
        public string UserName { get; set; }
        public string UserId { get; set; }
    }
    
    yourListBox.DisplayMember = "UserName";
    yourListBox.ValueMember = "UserId";
    
    yourListBox.Items.Add(new YourItem {
        UserName = "FooName",
        UserId = "FooId"
    });
    

提交回复
热议问题