2013-08-04 26 views
0

我想迭代通過我的窗口中的文本框,所以我可以對它們進行操作。這裏是我的代碼:我無法迭代槽文本框

foreach (Control c in Controls) 
{ 
    if (c is System.Windows.Forms.TextBox) 
    { 
     MessageBox.Show(c.Name); 
    } 
} 

我已經把斷點與if行了,我的程序到達該斷點,但它並沒有達到MessageBox線......在哪裏錯誤? (我c is Button測試這和它的工作...)

+9

確定文本框是*直接*形式的子項?他們不是(例如)在面板上? –

+0

實際上,他們是面板的孩子...我在這種情況下能做什麼,因爲我在這個窗口上也有很多面板... – Victor

+0

@Victor遞歸方法循環遍歷窗體上的所有控件需要。 –

回答

2

這是相當如此簡單,我不想添加回答,但對於OP的請求:

private void CheckTextBoxesName(Control root){ 
    foreach(Control c in root.Controls){ 
     if(c is TextBox) MessageBox.Show(c.Name); 
     CheckTextBoxesName(c); 
    } 
} 
//in your form scope call this: 
CheckTextBoxesName(this); 
//out of your form scope: 
CheckTextBoxesName(yourForm); 
//Note that, if your form has a TabControl, it's a little particular to add more code, otherwise, it's almost OK with the code above. 
+0

我知道如何稱呼它:p – Victor

+0

@Victor看到我的編輯,很簡單。 –

+0

@keyboardP :))幽默downvoter? –

1

這會幫助你

foreach (TextBox t in this.Controls.OfType<TextBox>()) 
    { 
     MessageBox.Show(t.Name); 
    } 

備選:

void TextBoxesName(Control parent) 
{ 
    foreach (Control child in parent.Controls) 
    { 
     TextBox textBox = child as TextBox; 
     if (textBox == null) 
      ClearTextBoxes(child); 
     else 
      MessageBox.Show(textbox.Name); 
    } 
} 

    TextBoxesName(this); 
+0

第一個代碼無法在OP的情況下工作,我們只有一個解決方案,我們使用遞歸方法。 –

+0

@KingKing,發表一個答案,如果你知道它! – Victor