Stefan
Stefan

Reputation: 281

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

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!

Upvotes: 27

Views: 69632

Answers (4)

Carlos Alma
Carlos Alma

Reputation: 51

You can override "ToString" method.

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

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

Upvotes: 2

Evren Kuzucuoglu
Evren Kuzucuoglu

Reputation: 3885

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;

Upvotes: 18

Frédéric Hamidi
Frédéric Hamidi

Reputation: 262939

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

Upvotes: 44

BrunoLM
BrunoLM

Reputation: 100331

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

Upvotes: 1

Related Questions