Adsence750x90

Tuesday, February 17, 2009

How to Clear All Values in Page -tutorials and code snippet

How to Clear all controls values like TextBox1,DropDownList?

We can get Page controls from Page.Controls. each controls are child controls of other page element in asp.net.
protected void Button1_Click(object sender, EventArgs e)
    {
        ClearAllControlsValues(Page.Controls, 0);
    }

    private void ClearAllControlsValues(ControlCollection controls, int depth)
    {
        foreach (Control ctrl in controls)
        {
            if (ctrl.GetType().ToString() == "System.Web.UI.WebControls.TextBox")
            {
                TextBox txt = (TextBox)FindControl(ctrl.ID);
                if (txt != null)
                {
                    txt.Text = string.Empty;
                }
            }
            if (ctrl.GetType().ToString() == "System.Web.UI.WebControls.DropDownList")
            {
                DropDownList dDownList = (DropDownList)FindControl(ctrl.ID);
                if (dDownList != null)
                {
                    dDownList.SelectedIndex = 0;
                }
            }
            if (ctrl.Controls != null)
            {
                ControlCollection(ctrl.Controls, depth + 1);
            }
        }
    }

No comments: