1

I've got this code to assign a Dictionary to a combobox:

Dictionary<String, String> dict = ReportRunnerConstsAndUtils.GetReportGeneratorsDictionary();
comboBoxReportRunners.DataSource = new BindingSource(dict, null);
comboBoxReportRunners.DisplayMember = "Key";
comboBoxReportRunners.ValueMember = "Value";

I want to verify that the items' DisplayMembers and ValueMembers are what I hope they are. This seems like a logical way to test that:

foreach (var v in comboBoxReportRunners.Items)
{
    MessageBox.Show(v.DisplayMember.ToString());
    MessageBox.Show(v.ValueMember.ToString());
}

...but it doesn't compile; I get, "'object' does not contain a definition for 'DisplayMember' and no extension method 'DisplayMember' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)'" and the same err msg for 'ValueMember'

What do I need to see (one time only) what values are stored as each Items' DisplayMember and ValueMember?

B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862

2 Answers2

3

try this way:

foreach (KeyValuePair<string,string> v in comboBoxReportRunners.Items)
{
    MessageBox.Show(v.Key.ToString());
    MessageBox.Show(v.Value.ToString());
}  

Dictionary stores data using KeyValuePair

Rei
  • 56
  • 2
2

DisplayMember and ValueMember are properties of the combo box and not of the items contained in it. As the error says, the items in the combo box are of type Object, so if you want to access their properties you have to to a cast first. You data source is of type Dictionary<String, String> which is a collection of KeyValuePair<string,string>, so in the foreach loop you have to use this type (there are two possible ways):

foreach (KeyValuePair<string,string> v in comboBoxReportRunners.Items)
{
    MessageBox.Show(v.Key.ToString());
    MessageBox.Show(v.Value.ToString());
}

or

foreach (var v in comboBoxReportRunners.Items)
{
    KeyValuePair<string,string> val = v as KeyValuePair<string,string>;
    MessageBox.Show(val.Key.ToString());
    MessageBox.Show(val.Value.ToString());
}