Here I can't see even a single correct answer for this question (in WinForms tag) and it's strange for such frequent question.
Items of a ListBox
control may be DataRowView
, Complex Objects, Anonymous types, primary types and other types. Underlying value of an item should be calculated base on ValueMember
.
ListBox
control has a GetItemText
which helps you to get the item text regardless of the type of object you added as item. It really needs such GetItemValue
method.
GetItemValue Extension Method
We can create GetItemValue
Extension Method to get item value which works like GetItemText
:
using System;
using System.Windows.Forms;
using System.ComponentModel;
public static class ListControlExtensions
{
public static object GetItemValue(this ListControl list, object item)
{
if (item == null)
throw new ArgumentNullException("item");
if (string.IsNullOrEmpty(list.ValueMember))
return item;
var property = TypeDescriptor.GetProperties(item)[list.ValueMember];
if (property == null)
throw new ArgumentException(
string.Format("item doesn't contain '{0}' property or column.",
list.ValueMember));
return property.GetValue(item);
}
}
Using above method you don't need to worry about settings of ListBox
and it will return expected Value
for an item. It works with List<T>
, Array
, ArrayList
, DataTable
, List of Anonymous Types, list of primary types and all other lists which you can use as data source. Here is an example of usage:
//Gets underlying value at index 2 based on settings
this.listBox1.GetItemValue(this.listBox1.Items[2]);
Since we created the GetItemValue
method as an extension method, when you want to use the method, don't forget to include the namespace which you put the class in.
This method is applicable on ComboBox
and CheckedListBox
too.