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!
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"
});
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;
string userid = listbox.SelectedValue ONLY works if you set the ListBox.DataSource