2011-08-11 188 views
1

我有幾個輸入文本框,然後幾個結果。 是否有任何快捷方式來清除表單上的所有條目?清除所有文本框(任何快捷方式)

例如aTextBox.Clear();

+1

我知道做到這一點是遞歸通過控制樹遍歷的唯一方法,檢查類型,並明確控制。 http://stackoverflow.com/questions/4811229/how-to-clear-the-text-of-all-textboxes-in-the-form – RoccoC5

回答

8

如果所有的文本框的形式直接孩子,你可以使用LINQ:

yourForm.Controls.OfType<TextBox>().ToList().ForEach(textBox => textBox.Clear()); 
+1

+1,尼斯查詢! – sll

1

您需要循環對所有形式的控制和檢查,如果類型爲文本框,然後。文本=的String.Empty

+0

考慮實施這個作爲擴展方法。 –

+0

也作爲提到的刪除註釋,您還需要檢查表單上的所有容器控件。 –

+0

是的,這將導致嵌套循環,所以@Frédéric回答是更好http://stackoverflow.com/questions/7034161/clear-all-textboxes-any-shortcut/7034178#7034178 –

1
var cntrlCollections = GetAll(this,typeof(TextBox)); 

     foreach (Control ctrl in cntrlCollections) 
     { 

      if (ctrl is TextBox) 
      { 
       ctrl.Text = " "; 
      } 
     }  

public IEnumerable<Control> GetAll(Control control, Type type) 
    { 
     var controls = control.Controls.Cast<Control>(); 

     return controls.SelectMany(ctrl=>GetAll(ctrl,type)).Concat(controls).Where 
       (c=>c.GetType() ==type); 
    } 

調用此函數類似上面的單擊事件來清除所有文本框。希望這會對你有所幫助。

1

評論弗雷德裏克 - 你需要使用ActiveForm yourform.ActiveForm.Controls. ...

怎麼一回事,因爲yourform.Controls. ...刪除一個錯誤:

An object reference is required for the non-static field, method, or property 'System.Windows.Forms.Control.Controls.get

適用於VS2012Express

相關問題