簡體   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