ardatosun
ardatosun

Reputation: 467

How to iterate over the controls inside an asp.net page?

This might be a noob question but I couldn't understand why it didn't work. I want to clear all the forms inside the page after the user has entered a new record. I call it right before my OnClick method finishes. My page also does not have a parent Master page and I just want to iterate over the Controls I want, not all. This is my code: (I know that if I use it like this it will mess with the DropDownList items, I will change it after I get the logic of getting the controls in page)

public void ClearForms()
        {
            foreach (var item in Page.Controls)
            {
                if (item is TextBox)
                {
                    ((TextBox)item).Text = String.Empty;
                }
                if (item is ListItem)
                {
                    ((ListItem)item).Text = "Choose...";
                    ((ListItem)item).Value = "-1";
                }
            }
        }

The program also does not go inside the if statements. I tried to get type by item.GetType() but it said it wasn't valid in the context.

Upvotes: 2

Views: 3185

Answers (1)

Karim AG
Karim AG

Reputation: 2193

You either have to use a recursive function and pass a control as a parameter to that function, the function will then loop through the controls inside that control, see Loop through all controls on asp.net webpage

Or you have to put your listboxes and textboxes inside a panel and loop through the controls inside that panel, something like this:

<asp:Panel ID="pnl" runat="server">
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</asp:Panel>

<asp:Button ID="btnClear" runat="server" Text="Clear" OnClick="btnClear_Click" />

And the code behind:

protected void btnClear_Click(object sender, EventArgs e)
    {
        ClearForms(pnl);
    }

    public void ClearForms(Control c)
    {
        foreach (var item in c.Controls)
        {
            if (item is TextBox)
            {
                ((TextBox)item).Text = String.Empty;
            }
            if (item is ListItem)
            {
                ((ListItem)item).Text = "Choose...";
                ((ListItem)item).Value = "-1";
            }
        }
    }

Explanation to your case: the control.Controls only fetches the first level controls inside the control, so when you call Page.Controls, it only fetches whatever server controls are there on your page's first level of elements.

hope this helps...

Upvotes: 2

Related Questions