当转换为ComboBox []时,Controls.Find方法不返回任何内容

时间:2016-04-17 12:52:01

标签: c# winforms combobox

我有一个方法可以在标签页上的所有控件中搜索并返回一个匹配字符串(Controls.Find方法)的方法。因为我确定只能找到一个控件,并且该控件是一个组合框,我试图将它转换为但它的行为很奇怪。

此代码正确执行:

private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        ComboBox cb = sender as ComboBox;
        String Name = cb.Name;
        Name = Name.Replace("Rank", "Target");
        Control[] ar = cb.Parent.Controls.Find(Name, false);
        MessageBox.Show(ar.Length.ToString());
        if (ar.Length > 1)
        {
            MessageBox.Show("More than one \"Target\" combo box has been found as the corresponding for the lastly modified \"Rank\" combo box.");
        }
        else
        {
            for (int i = cb.SelectedIndex; i < Ranks.Count - 1; i++)
            {
                //ar[0].Items.Add(Ranks[i]); - this does not work, since Controls don't have a definition for "Items"
            }
        }
    }

此代码的Controls.Find方法不返回任何内容:

private void Enchantments_ComboBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        ComboBox cb = sender as ComboBox;
        String Name = cb.Name;
        Name = Name.Replace("Rank", "Target");
        ComboBox[] ar = (ComboBox[])cb.Parent.Controls.Find(Name, false); //Also tried "as ComboBox, instead of "(ComboBox)" if it matters
        MessageBox.Show(ar.Length.ToString()); //Raises an exception as arr[] is null
        if (ar.Length > 1)
        {
            MessageBox.Show("More than one \"Target\" combo box has been found as the corresponding for the lastly modified \"Rank\" combo box.");
        }
        else
        {
            for (int i = cb.SelectedIndex; i < Ranks.Count - 1; i++)
            {
                ar[0].Items.Add(Ranks[i]);
            }
        }
    }

我想知道为什么它在作为ComboBox进行投射时没有返回任何内容以及我如何能够缓解这种行为。

1 个答案:

答案 0 :(得分:2)

查看Find方法签名:

public Control[] Find(string key, bool searchAllChildren)

结果是控制数组的类型。即使数组的所有控件都是ComboBox类型,结果也不是ComboBox[]的类型,所以转换返回null。

如果您需要ComboBox数组,只需使用:

ComboBox[] result = cb.Parent.Controls.Find(Name, false).OfType<ComboBox>().ToArray();

此外,如果您确定所有返回的元素都属于ComboBox类型,那么您也可以使用Cast<ComboBox>()代替OfTYpe<ComboBox>()

当所有元素属于同一类型时,您可以使用Cast<T>,当某些元素的类型可能为K但您只需要T类型的元素时,您可以使用OfType<T>