0

I fill out a ComboBox using below code:

cbxLines.DisplayMember = "Value";
cbxLines.ValueMember = "Key";
cbxLines.DataSource = new BindingSource(GetProductionLines(), null);

private Dictionary<int, string> GetProductionLines()

Now I want to fill out a ListView with every DisplayMember from the ComboBox among other info:

lvSelectedSetup.Items.Clear();
for (int i = 0; i <= cbxLines.Items.Count - 1; i++)
{
     ListViewItem item = new ListViewItem();
     item.SubItems.Add(cbxLines.Items[i].ToString());  <-- How to Get DisplayMember
     item.SubItems.Add(cbxFromDate.Text);
     item.SubItems.Add(cbxToDate.Text);
     lvSelectedSetup.Items.Add(item);
}

But I don't know how to get either the ValueMember or DisplayMember from the ComboBox.

I was trying doing the following, but get stuck:

item.SubItems.Add(cbxLines.Items[i].GetType().GetProperty(cbxLines.ValueMember).GetValue(cbxLines,null))

Any Advice?

Somebody
  • 2,667
  • 14
  • 60
  • 100

1 Answers1

5

Gets the key in the key/value pair.

   ((KeyValuePair<int, string>)cbxLines.Items[i]).Key

Gets the value in the key/value pair.

((KeyValuePair<int, string>)cbxLines.Items[i]).Value
Jacob Seleznev
  • 8,013
  • 3
  • 24
  • 34
  • Outstanding! By the way, I've figured it out how to make my approach work: `item.SubItems.Add(cbxLines.Items[0].GetType().GetProperty(cbxLines.DisplayMember).GetValue(cbxLines.Items[i], null).ToString());` it is a bit longer of course :) – Somebody Dec 23 '14 at 21:24
  • @Somebody: it is also a _lot_ slower than doing it the way Jacob shows. Avoid reflection if you can. And one usually can. Note also that you really only need this for the `DisplayMember` member. You can get the `ValueMember` member's value straight from the `ComboBox.SelectedValue` property. – Peter Duniho Dec 23 '14 at 21:39