Clear all textboxes and reset dropdownlist After CLEAR button is Clicked by looping through page conrtols in ASP.net :

Dec 21, 2011 By Anil Gaikwad

Many time when you are writing a code a time comes when you need to clear all data which is entered on page or reset the page that time either you clear all textbox by writing textbox1.text = "" or you can use below code.

  • In below code you loop through controls that are present in FORM
  • Then we check it is textbox or dropdownlist you can check as per your requirement and then do the required operation on it like clearing the text or reseting it
protected void btnClear_Click(object sender, EventArgs e) { foreach (Control c in form1.Controls) { if (c.GetType() == typeof(TextBox)) { ((TextBox)(c)).Text = ""; } else if (c.GetType() == typeof(DropDownList)) { ((DropDownList)(c)).SelectedIndex = 0; } } }

if you want perticular operation for perticular textbox then you can also do that by checking ID of that control as per example shown below

protected void Button1_Click(object sender, EventArgs e) { foreach (Control c in form1.Controls) { if (c.GetType() == typeof(TextBox)) { ((TextBox)(c)).Text = ""; if (((TextBox)(c)).ID == "TextBox1") { ((TextBox)(c)).Enabled = false; } } else if (c.GetType() == typeof(DropDownList)) { ((DropDownList)(c)).SelectedIndex = 0; } } }