-3

I have a tabControl that contains many textBoxes, I want to add a button to clear all textBoxes's texts at once, I tried this code:

private void ClearButton_Click(object sender, EventArgs e)
{
    foreach (TextBox t in tabControl1.SelectedTab.Controls)
    {
        t.Clear();
    }
}

But this code doesn't work, i got this error message :

Unable to cast object of type 'System.Windows.Forms.Button' to type 'System.Windows.Forms.TextBox

What is wrong in this code?

braX
  • 11,506
  • 5
  • 20
  • 33
user4374239
  • 93
  • 2
  • 11

4 Answers4

4

You're trying to iterate through every Control, some of which are not TextBox controls.

You can use OfType to specify which controls you're interested in, instead:

foreach (TextBox t in tabControl1.SelectedTab.Controls.OfType<TextBox>())
{
    t.Clear();
}
Grant Winney
  • 65,241
  • 13
  • 115
  • 165
2

you get all controls (not only the TextBoxes) in the foreach loop

try something like this:

foreach (Control t in tabControl1.SelectedTab.Controls)
{
    if(t is TextBox)
        ((TextBox)t).Clear();
}
Stefan Woehrer
  • 680
  • 4
  • 12
2

Try this code:

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 ClearButton_Click(object sender, EventArgs e)
{
    ClearTextBoxes(tabControl1.SelectedTab);
}
user4340666
  • 1,453
  • 15
  • 36
0

Not all controls are textboxes. Do it this way:

private void ClearButton_Click(object sender, EventArgs e)
{
    foreach (var control in tabControl1.SelectedTab.Controls)
    {
        if(control is TextBox)
        {
             TextBox t = (TextBox)control;
             t.Clear();
             // or short:
             // ((TextBox) control).Clear();
        }
    }
}
DrKoch
  • 9,556
  • 2
  • 34
  • 43