Clear the text of all text fields in the selected tab

I have a form with tab control , and each tab has a number of textboxes , labels and buttons . I want the user to be able to clear all the text in the text boxes of the selected tab.

I tried

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

In the above code, InvalidCastException with the message Unable to cast object of type 'System.Windows.Forms.Button' to type 'System.Windows.Forms.TextBox .

Pls what i did wrong and how can i fix it?

+7
c # winforms textbox
source share
5 answers

Found it online and it worked

  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); } 
+4
source share

Use OfType<T>() in the foreach loop.

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

Alternative:

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

Using can simply iterate over all the controls on the selected tab and before clearing the text, check if there is a control type TextBox and clear the text.

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

if you have text fields nested in your tabcontrol. you need to write a recursive method here, because ofType method will not return your nested text fields.

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

Alternatively, if you only have text fields at the basic TabControl level, you can use this

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

All Articles