Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make ListBox items have a different value than item text

Tags:

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.

like image 835
CasperT Avatar asked May 15 '09 08:05

CasperT


People also ask

Which property of ListBox is used to control the number of items?

To determine the total number of list box's items, you can use the wItemCount property, which belongs to the Win32ListBox object.

What method can we use to add the items into the ListBox?

To insert an item into the list box at a specific position, use the Insert method. To add a set of items to the list box in a single operation, use the AddRange method.


1 Answers

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; }; } 
like image 196
Fredrik Mörk Avatar answered Oct 02 '22 06:10

Fredrik Mörk