如何验证我已经分配给组合框的字典值是我认为的?

时间:2015-12-28 17:23:02

标签: c# winforms dictionary combobox valuemember

我已经将此代码分配给组合框:

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

我想核实这些物品&#39; DisplayMembers和ValueMembers是我希望它们。这似乎是测试它的合理方式:

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

......但它没有编译;我明白了,&#34; &#39; object&#39;不包含&#39; DisplayMember&#39;的定义没有扩展方法&#39; DisplayMember&#39;接受类型&#39;对象&#39;的第一个参数。可以找到(你错过了使用指令或汇编引用吗?)&#39; &#34;对于&#39; ValueMember&#39;

,同样的错误消息

我需要查看(仅限一次)每个项目存储的值。 DisplayMember和ValueMember?

2 个答案:

答案 0 :(得分:3)

尝试这种方式:

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

Dictionary使用KeyValuePair存储数据

答案 1 :(得分:2)

DisplayMemberValueMember是组合框的属性,而不是其中包含的项目的属性。如错误所示,组合框中的项目类型为Object,因此如果要访问其属性,则必须先进行强制转换。您的数据源类型为Dictionary<String, String>,是KeyValuePair<string,string>的集合,因此在foreach循环中您必须使用此类型(有两种可能的方式):

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

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());
}