[英]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)?是否可以通过对象携带两个值(每列的每个值/属性
ListBox.Items.Add()
的方式将对象传递给ListBox.Items.Add()
并且在获取所选项目时,我们将有一个带有两个值的对象值(也许作为对象的属性)?
Is such a thing possible in C#?在 C# 中可以实现这样的事情吗? (.NET 4.5)
(.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
:您可以将将数据与名称配对的对象传递给您的
ListBox
,并使用DisplayMember
和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.现在您的列表框显示相同的字符串列表,但为最终用户选择返回的值会有所不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.