1
我有一個方法可以在選項卡的所有控件中搜索並返回匹配字符串的方法(Controls.Find方法)。由於我確信只有一個控件將被找到,並且該控件是一個組合框,所以我試圖將其投射出去,但這很奇怪。Controls.Find方法在作爲ComboBox投射時不會返回任何東西[]
這段代碼執行正確:
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]);
}
}
}
我不知道爲什麼它的時候投作爲一個組合框返回任何內容,我怎麼能緩解這種行爲。
非常感謝!所以,我的錯誤並不知道將某些類型轉換爲某種類型並不能解決方法返回的類型。 – mathgenius
當您嘗試將SomeValue強制轉換爲SomeType時,只有當SomeValue實際上屬於SomeType類型時,強制轉換纔會成功。你的錯誤在這裏,你預計演員可以將'Control []'轉換爲'ComboBox []'。包含一些組合框的控件數組不是'ComboBox []'類型。若要將其轉換爲組合框列表,如果您知道所有元素都是ComboBox類型,則可以使用Cast(),如果元素也可能包含其他控件,則可以僅將結果限制爲組合框,使用'OfType ()'。 –