0
    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?

Edited by Black_Lion

3
Contributors
4
Replies
22
Views
4 Years
Discussion Span
Last Post by annaharris
0

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();
        }
}

Edited by tinstaafl

0

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.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.