2011-12-16 29 views
2

感謝這裏的幫助,我設法遞歸循環遍歷我的winform中的所有控件,並找到我的子分類控件,但是當我嘗試更新我的用戶定義的屬性_key和_value對象CTRL不公開他們:(我使用 ctrlContainer 下面是這個無法在winforms控件中找到新的子分類屬性

foreach (Control ctrl in ctrlContainer.Controls) 
{ 
    // code to find my specific sub classed textBox 
    // found my control 
    // now update my new property _key 
    ctrl._key does not exist :(

    I know the ctrl exists and is valid because ctrl.Text = "I've just added this text" works. 
    _key is visible when looking at the control in the form designer. 
} 

誰能給我一個提示,我在做什麼錯? 由於通過調用形式。

回答

3

這是因爲您的參考是類型Controlforeach (Control ctrl),我假設不是你的分類控制。該引用只會理解屬於它的成員,_key可能屬於派生類。試試這個:

foreach (Control ctrl in ctrlContainer.Controls) 
{ 
    // code to find my specific sub classed textBox 
    // found my control 
    // now update my new property _key 
    if (ctrl is MyControl) 
    { 
     MyControl myControl = (MyControl)ctrl; 
     myControl._key = ""; 
    } 
} 

或者你可以改變你的迭代器來找到你的控件的實例,就像塞巴斯蒂安所建議的那樣。這將是更乾淨的代碼。

+0

這一個爲我工作,因爲的foreach(在ctrlContainer.Controls.OfType ()VAR CTRL)搞砸了,看起來對任何文本框控件如組盒內部的代碼。 – Hunt 2011-12-16 16:12:18

4

_key不存在,因爲您正在查看Control

嘗試做:

foreach (var ctrl in ctrlContainer.Controls.OfType<MyControl>()) 
{ 
    ctrl._key = "somthing"; 
} 
+0

這樣,你只是迭代當前控件類型的控件的容器,它確保具有`_key`屬性;按照你在問題中發佈的方式,你不能保證所有的控件都是這種類型的(事實上他們不會)。 – 2011-12-16 11:13:34

相關問題