选定选项卡中所有文本框的清除文本

我有一个具有tab control的表单,每个选项卡都有许多textboxeslabelsbuttons 。 我想让用户清除所选标签的文本框中的所有文本。

我试过了

  private void resetCurrentPageToolStripMenuItem_Click(object sender, EventArgs e) { foreach (TextBox t in tabControl1.SelectedTab.Controls) { t.Text = ""; } } 

上面的代码抛出InvalidCastException并使用Message Unable to cast object of type 'System.Windows.Forms.Button' to type 'System.Windows.Forms.TextBox InvalidCastException Unable to cast object of type 'System.Windows.Forms.Button' to type 'System.Windows.Forms.TextBox

请问我做错了什么,我该怎么纠正呢?

在foreach循环中使用OfType()

 private void resetCurrentPageToolStripMenuItem_Click(object sender, EventArgs e) { foreach (TextBox t in tabControl1.SelectedTab.Controls.OfType()) { t.Text = ""; } } 

替代方案:

 foreach (Control control in tabControl1.SelectedTab.Controls) { TextBox text = control as TextBox; if (text != null) { text.Text = ""; } } 

在网上找到它并且它有效

  void ClearTextBoxes(Control parent) { foreach (Control child in parent.Controls) { TextBox textBox = child as TextBox; if (textBox == null) ClearTextBoxes(child); else textBox.Text = string.Empty; } } private void resetCurrentPageToolStripMenuItem_Click(object sender, EventArgs e) { ClearTextBoxes(tabControl1.SelectedTab); } 

使用可以简单地遍历所选选项卡中的所有控件,并在清除文本之前检查control type是否为TextBox并清除文本。

  foreach (Control item in tabControl1.SelectedTab.Controls) { if (item.GetType().Equals(typeof(TextBox))) { item.Text = string.Empty; } } 

如果您的tabcontrol中嵌套了文本框。 你需要在这里编写一个递归方法,因为ofType方法不会返回你的嵌套文本框。

  private void ResetTextBoxes(Control cntrl) { foreach(Control c in cntrl.Controls) { ResetTextBoxes(c); if(c is TextBox) (c as TextBox).Text = string.Empty; } } 

或者,如果您只在TabControl的基础级别上有文本框,则可以使用它

 foreach(var tb in tabControl1.OfType()) { tb.Text = string.Emtpy; } 
  var textBoxNames = this.tabControl1.SelectedTab.Controls.OfType(); foreach (var item in textBoxNames) { var textBoxes = tabControl1.SelectedTab.Controls.Find(item.Name, true); foreach (TextBox textBox in textBoxes) { textBox.Clear(); } }