27

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 listbox.Items.Add(object);) and show the username of that object?

Thnx!

4 Answers 4

44

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"
});
Sign up to request clarification or add additional context in comments.

Comments

18

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;

1 Comment

string userid = listbox.SelectedValue ONLY works if you set the ListBox.DataSource
2

You can override "ToString" method.

class User
{
    public string username { set; get; }
    public string userid { set; get; }

    public override string ToString()
    {
        return username;
    }
}

Comments

1

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 });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.