Monday, June 15, 2009

how to clear controls in asp.net c#

1. how to clear controls in asp.net c#
private void ClearControls(Control parent)
{
foreach (Control _ChildControl in parent.Controls)
{
if ((_ChildControl.Controls.Count > 0))
{
ClearControls(_ChildControl);
}
else
{
if (_ChildControl is TextBox)
{
((TextBox)_ChildControl).Text = string.Empty;
}
else
if (_ChildControl is CheckBox)
{
((CheckBox)_ChildControl).Checked = false;
}

}
}
}

At Calling Statement send reference of page “this”. For example, ClearControls(this)

2. Ways to Clear Controls values in the Page
1. Creating method that would loop through the page controls and clear its values accordingly like:
private void ClearControls()

{

foreach (Control c in Page.Controls)

{

if (c.GetType().ToString() == "System.Web.UI.WebControls.TextBox")

{

TextBox tb = (TextBox)c;

if (tb != null)

{

tb.Text = string.Empty;

}

}

if (c.GetType().ToString() == "System.Web.UI.WebControls.DropDownList")

{

DropDownList ddl = (DropDownList)c;

if (ddl != null)

{

ddl.ClearSelection();

}

}

}

2. Creating a generic Recursive FindControl method that would search all the Controls in the page and reset their values.
public static void ClearControls(Control Parent)

{

if (Parent is TextBox)

{ (Parent as TextBox).Text = string.Empty; }

else

{

foreach (Control c in Parent.Controls)

ClearControls(c);

}

}

//Then call the method like this

ClearControls(Page)

3. Using HTML Input type RESET Button
input type="reset" value="Reset form

4. Redirect to the same page using Response.Redirect method.
Response.Redirect("YourPage.aspx");

No comments: