protected void Button1_Click(object sender, EventArgs e)
    {
          ClearTextBoxes(this);
    }


    public void ClearTextBoxes(Control control)
    {
           foreach (Control c in control.Controls)
           {
              if (c is TextBox)
              {
                 ((TextBox)c).Text = " ";
              }


     }

Hi all. I am writing a program using Microsoft Visual Web Developer. I have 3 textboxes (TextBox1, TextBox2 and TextBox3) and a button. I want to use a foreach loop to clear textboxes.

For some reason this code doesnt work on a Webform. While debugging it, the debugger skips the line: "if (c is TextBox)" and so the textboxes dont get cleared. Here "control = {ASP.default_aspx}"

When I use the below code in Microsoft Visual C# with a windows form it works. What could be wrong?

Recommended Answers

All 4 Replies

it might be better to use the oftype property in your foreach loop;

 public void ClearTextBoxes(Control control)
{
        foreach (TextBox c in control.Controls.OfType<TextBox>())
        {
            c.Clear();
        }
}

Thanks a lot!

If that solved it for you, please mark this. Thanks

It doesn't look anything wrong in your code and it also works fine in my webform. It's hard to figure out the issue.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.