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

后端 未结 4 1819
情歌与酒
情歌与酒 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;
    
    0 讨论(0)
  • 2020-12-09 09:38

    Set the DataTextField and DataValueField

    ListBox a = new ListBox();
    a.DataTextField = "username";
    a.DataValueField = "userid";
    

    To add using .Add method you can use:

    a.Items.Add(new ListItem() { Value = User.ID, Text = User.Name });
    
    0 讨论(0)
  • 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"
    });
    
    0 讨论(0)
  • 2020-12-09 09:43

    You can override "ToString" method.

    class User
    {
        public string username { set; get; }
        public string userid { set; get; }
    
        public override string ToString()
        {
            return username;
        }
    }
    
    0 讨论(0)
提交回复
热议问题