简体   繁体   中英

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM