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

后端 未结 4 1832
情歌与酒
情歌与酒 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:22

    You can use the DisplayMember property of your listBox.

    listbox.DisplayMember = "username";
    

    There is also an equivalent property to define the actual value, that you could use to retrieve the userid. For example if you define your list like this:

    listbox.DisplayMember = "username";
    listbox.ValueMember = "userid";
    var item1 = new MyType { username = "user1", userid = "id1" }; // Create an item for the list
    
    listbox.Items.Add(item1); // Add the item
    listbox.SelectedIndex = 0; // Selects the first item
    

    Then you can reference the objects in the list by 3 different ways (item, value or text) like this:

    MyObject newItem = (MyObject) listbox.SelectedItem; // Gets the selected MyType
    // OR
    string username = listbox.Text; // Gets the selected user name using the DisplayMember property of the listbox
    // OR
    string userid = listbox.SelectedValue; // Gets the selected user's userid using the ValueMember property of the listbox
    

    You can also set the selected item the same 3 different ways:

    listbox.SelectedItem = item1;
    // OR
    listbox.Text = item1.username;
    // OR
    listbox.SelectedValue = item1.userid;
    

提交回复
热议问题