Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Listbox: How to add data in addition to text for each item

Consider the following text as two lists(separated with ':'), as you can see the second rows are always unique but items in the first row can be repetitive;

Book:m234
Clover:h67
Pencil:a12
Book:x67

I want to populate a listbox with items in the first column(Book, Clover, ...) but the problem is that when I'm going to retrieve the selected item in the listbox, I can't be sure about it's respective value in second column. (for example in case of 'Book');

NOTE: I'm not looking for any workaround for solving this problem because there are many. What I want to know is that:

Is it possible to pass and object to ListBox.Items.Add() in a way that the object carries two values(each value/property for each column) and in time of getting the selected item, we would have an object with the two values(maybe as the properties of the object)?

Is such a thing possible in C#? (.NET 4.5)

like image 908
wiki Avatar asked Dec 05 '25 09:12

wiki


1 Answers

You can pass objects that pair data with names to your ListBox, and control what gets displayed and what gets returned back to you by using DisplayMember and ValueMember:

class ListBoxItem {
    public string DisplayName {get;set;}
    public string Identifier {get;set;}
}
...
ListBox.Items.Add(new ListBoxItem {
    DisplayName = "Book", Identifier = "m234"
});
ListBox.Items.Add(new ListBoxItem {
    DisplayName = "Clover", Identifier = "h67"
});
ListBox.Items.Add(new ListBoxItem {
    DisplayName = "Pencil", Identifier = "a12"
});
ListBox.Items.Add(new ListBoxItem {
    DisplayName = "Book", Identifier = "x67"
});
ListBox.DisplayMember = "DisplayName";
ListBox.ValueMember = "Identifier";

Now your list box displays the same list of strings, but the values returned for end-user selections would be different.

like image 54
Sergey Kalinichenko Avatar answered Dec 06 '25 21:12

Sergey Kalinichenko