How to get the value from a WinForms.Listbox not databound.

I was faced with a bit of a challenge this morning. In WebForms getting the value of the selected item in a ListBox is pretty straight forward. However what i found in WebForms as a different story.

To complicate the process I was adding items to the listbox using the items collections add method.

If you look at the Intellisence for LIstBox.Items.Add expects a single argument of Object. Typically this is just the Text that is going to be displayed. However adding an item where the Text shows one thing, but the value is a different thing requires a slightly different approach

Step1. Add a new Class to your project that has a Text and Value property.
e.g.
private class ListItem
{
public string Text { get; set; }
public string Value { get; set; }
}
Step 2. When initializing the form, set the ListBox’s DisplayMember and ValueMember properties to your classes properties
e.g.
listBox1.ValueMember = “Value”;
listBox1.DisplayMember = “Text”;
Step 3. Add your items e.g.
listBox1.Items.Add(new ListItem(){ Text = “some text”, Value = “some value”});
Step 4. Read the value on the item being selected.
in the Listbox’s SelectedIndexChanged event read the value by casting the Listbox’s selected item as your custom class and then reading the property you need.
e.g. ((ListItem)listBox1.Items[listBox1.SelectedIndex]).Value

 

Hopefully that helps..