Reset values of Form controls in ASP.NET

It is very common requirement of Form to clear all controls in a single click, like Click on "Reset Button",Aim of this article is implement a generic method for clear/reset all control values in .NET web pages.

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class ResetDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void ResetBtn_Click(object sender, EventArgs e)
{
ResetFormControlValues(this); ;
}

private void ResetFormControlValues(Control parent)
{
foreach (Control c in parent.Controls)
{
if (c.Controls.Count > 0)
{
ResetFormControlValues(c);
}
else
{
switch (c.GetType().ToString())
{
case "System.Web.UI.WebControls.TextBox":
((TextBox)c).Text = "";
break;
case "System.Web.UI.WebControls.CheckBox":
((CheckBox)c).Checked = false;
break;
case "System.Web.UI.WebControls.RadioButton":
((RadioButton)c).Checked = false;
break;
case "System.Web.UI.WebControls.DropDownList":
((DropDownList)c).SelectedIndex = 0;
break;
}
}
}
}
}

First Create a method called ResetFormControlValues() with the following sample code in one class file. Then wherever and whenever we wants to clear/reset all control values in our web application pages, we can easily clear/reset all control values using that ResetFormControlValues() method.
Tags: , ,
Hot on Web:


About author