/// <summary> /// 清空所有的文本框 /// </summary> private void ClearAllTextBox() { foreach (Control control in this.groupBox1.Controls) { if(control is TextBox) { ((TextBox)control).Text = ""; } } }
其中IF語句也可以寫成這樣:
if (control.GetType().ToString()=="System.Windows.Forms.TextBox")
如果按鈕批量清空所有TextBox、comboBox、checkBox的數據,則代碼可以寫在這樣:
private void ClearTextBoxAndComboBoxAndCheckBox() { foreach (Control c in this.Controls) { if (c.GetType().ToString().Contains("TextBox")) { ((TextBox)c).Text = ""; } if (c.GetType().ToString().Contains("ComboBox")) { ((ComboBox)c).Text = ""; } if (c.GetType().ToString().Contains("CheckBox")) { ((CheckBox)c).Checked = false; } } }