C# – Getting the items of a ComboBox with its DataSource filled


Consider that there is a ComboBox which is populated through its DataSource property. Each item in the ComboBox is a custom object and the ComboBox is set with a DisplayMember and ValueMember.

IList<CustomItem> aItems = new List<CustomItem>();
//CustomItem has Id and Value and is filled through its constructor
aItems.Add(1, "foo"); 
aItems.Add(2, "bar");

myComboBox.DataSource = aItems;

Now the problem is that, I want to read the items as string that will be rendered in the UI. Consider that I don't know the type of each item in the ComboBox (CustomItem is unknown to me)

Is this possible ?

Best Solution


ComboBox1.DataSource = aItems;
ComboBox1.DisplayMember = "Value";

Getting the item:

CustomItem ci = ComboBox1.SelectedValue as CustomItem;

edit: If all that you want to get is a list of all of the display values of the combobox

List<String> displayedValues = new List<String>();
foreach (CustomItem ci in comboBox1.Items)
Related Question