让ListBox中的项目比项目文本不同的值 [英] Make ListBox items have a different value than item text
问题描述
我要一个的ListBox
全项目。虽然,每个项目应该有不同的价值。
因此,当用户选择一个项目,然后按下一个按钮,一个方法将被调用,这将使用select项具有价值。
I want a ListBox
full of items. Although, each item should have a different value.
So when the user selects an item and presses a button, a method will be called which will use the value the select item has.
我不知道。要揭示项目值用户
I don't want to reveal the item values to the user.
编辑:这不是ASP.NET,它是一个Windows窗体应用程序。我只是想在HTML的例子是易于阅读
This is not for ASP.NET, it's for a Windows Forms application. I just thought the HTML example would be easy to read.
我已经从HTML灵感:
I have the inspiration from HTML:
<form>
<input type="radio" name="sex" value="Value1" /> Male
<br />
<input type="radio" name="sex" value="Value2" /> Female
</form>
这也让我比用户看到使用不同的值。
This also allows me to use different values than what the user sees.
推荐答案
您可以选择什么做用ListBox的的DisplayMember显示。
You can choose what do display using the DisplayMember of the ListBox.
List<SomeData> data = new List<SomeData>();
data.Add(new SomeData() { Value = 1, Text= "Some Text"});
data.Add(new SomeData() { Value = 2, Text = "Some Other Text"});
listBox1.DisplayMember = "Text";
listBox1.DataSource = data;
当用户选择一个项目,你可以阅读从选定的数值(或任何其他财产)对象:
When the user selects an item, you can read the value (or any other property) from the selected object:
int value = (listBox1.SelectedItem as SomeData).Value;
更新:注意的DisplayMember仅适用于性能,而不是与领域,所以你需要改变你的类一点:
Update: note that DisplayMember works only with properties, not with fields, so you need to alter your class a bit:
public class SomeData
{
public string Value { get; set; };
public string Text { get; set; };
}
这篇关于让ListBox中的项目比项目文本不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!