2014-01-16 30 views
1

我想清除一個窗體使用C#函數。創建一個函數來清除窗體(C#)

我知道清理各個控件像

username.Clear(); 
password.Clear(); 

的方法,但是,這是一個大的形式明確的功能看起來有點彆扭。

我在網上找到了一個代碼,看起來像這樣。

private void ClearFields(System.Windows.Forms.Control.ControlCollection collection) 
{ 
    foreach (Control c in collection) 
    { 
     if (c.HasChildren) 
      ClearFields(c.Controls); 
     if (c is TextBox) 
     { 
      if (!string.IsNullOrEmpty(c.Text)) 
       c.Text = ""; 
     } 
    } 
} 

但是,對於此代碼,密碼字段本身不會被清除。我正在清除「TextBox」控件。我是否必須指定任何其他控件名稱來清除密碼字段,即使它們基本都是「TextBox」控件?

+0

此代碼是否可用?控件沒有文本屬性。 –

+1

沒有「密碼」控件,只是將TextBox.PasswordChar屬性設置爲非空字符。 –

+0

是的,我明白了。但是代碼適用於所有其他領域。 –

回答

2

你應該得到(如果你還想清除MaskedTextBoxRichTextBox也或TextBoxBase),這是TextBox控制的控制,要求他們Clear()方法:

private void ClearTextBoxes(ControlCollection controls) 
{ 
    foreach (Control c in collection) 
    { 
     if (c.HasChildren) 
     { 
      ClearTextBoxes(c.Controls); 
      continue; 
     } 

     TextBox tb = c as TextBox; // or TextBoxBase 
     if (tb != null) 
      tb.Clear(); 
    } 
} 

正如@Adriano已經指出的,「密碼」控件WinForms中的簡單文本框

+0

我很抱歉,但是,似乎我的功能指向了我之前寫過的手動清除功能。我的問題仍然存在,因爲此方法仍然不清除密碼MessageBox。它只是清除所有其他消息框,除了密碼之外。 –

+0

@MklRjv你在說什麼消息框?你是什​​麼定製功能? –

+0

我編輯了我的問題。請找到更新的代碼。我用來清除表單的功能只是手動清除所有的MessageBoxes。像username.Clear()和password.Clear()等。 –

相關問題