Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

c# - Make ListBox items have a different value than item text

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.

EDIT: This is not for ASP.NET, it's for a Windows Forms application. I just thought the HTML example would be easy to read.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

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; };
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...