繁体   English   中英

如何通过 ComboBox.Items 遍历字典的键

[英]How to iterate through the keys of a dictionary via ComboBox.Items

我的应用程序具有以下方法,该方法以前有效,但在重构为多个程序集后不再有效。

/// <summary>
/// Attempt to set the combobox to the item with the supplied string
/// </summary>
protected void SetComboBoxSelection(ComboBox cmb, string ItemText)
{
     if (cmb.DisplayMember.ToLower() == "key" && cmb.ValueMember.ToLower() == "value")
     {
          foreach (KeyValuePair<string, object> item in cmb.Items)
          {
               if (item.Key == ItemText || ((string)item.Key).HasPatternMatch(ItemText))
               {
                    cmb.SelectedItem = item;
                    return;
               }
          }     
     }
}

我得到以下异常:

System.InvalidCastException: 'Unable to cast object of type 'System.Collections.Generic.KeyValuePair`2[System.String,NetworkSyncObjects.NetworkFolder]' to type 'System.Collections.Generic.KeyValuePair`2[System.String,System.Object]'.'

此方法用于设置各种组合框的选择,每个组合框都有不同的字典类型,但所有组合框都将“键”作为字符串类型。 现在,由于(释义)“那是不允许的。这是一个重复的问题,只能解释原因”的非常无益的答案,我之前的问题被关闭了。

再次,此代码有效。 但现在没有了。 我知道它显然不起作用,因为列表中的项目假定无效。 (重复的答案是关于投射列表本身,而不是列表中的项目)。

这是我尝试过的

  • 使用dynamic item -> 不编译。
  • 使用KeyValuePair<string,dynamic> -> 编译但得到与上述相同的运行时异常
  • 使用var obj as dynamic / var obj as KeyValuePair<string,object> -> 两者总是导致 null obj

问题:

如何修改此方法以使用其 itemsource 为Dictionary<string,T>的任何组合框,其中 T 是各种类型的对象)?

例如,一些将是: Dictionary<string,NetworkFolder> , Dictionary<string,FileInfo> , Dictionary<string,DirectoryInfo> , Dictionary<string,int>

据我所知,除非您强制转换列表,否则无法访问列表中 KeyValuePair 的Key部分,如果不明确调用 keyvaluepair 中的确切类型,显然是不允许的。 再一次,不知道为什么这行得通,而现在不行。 但我在这里。

更新方法,使用IDictionary接口并直接访问数据源绑定是我解决它的方法。

从这篇文章修改: https ://stackoverflow.com/a/55850559/12135042

protected void SetComboBoxSelection(ComboBox cmb, string ItemText)
        {
            if (cmb.DisplayMember.ToLower() == "key" && cmb.ValueMember.ToLower() == "value")
            {
                IDictionary Items = (IDictionary)((BindingSource)cmb.DataSource).DataSource;
                int i = 0;
                foreach (string item in Items.Keys)
                {
                    if (item == ItemText || item.HasPatternMatch(ItemText))
                    {
                        cmb.SelectedIndex = i;
                        return;
                    }
                    i++;
                }
                    
            }
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM