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.
To determine the total number of list box's items, you can use the wItemCount property, which belongs to the Win32ListBox object.
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.
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; }; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With