Create new account I forgot my password    

ASP.NET 2.0 ‘Easy To Do’ Series – Reset values of all controls using ASP.NET 2.0 and JavaScript
Rating: 43 user(s) have rated this article Average rating: 4.4
Posted by: Suprotim Agarwal, on 9/29/2007, in category "ASP.NET 2.0 & 3.5"
Views: this article has been read 25537 times
Abstract: I recently received a request to cover some basic tips that could be useful for anyone using ASP.NET 2.0, in their projects. I am creating the 'ASP.NET 2.0 Easy To Do' series to cover such topics. In this article we will see how easy it is to use recursion and clear values of all controls on a page using ASP.NET 2.0 and JavaScript

Reset values of all controls using ASP.NET 2.0 and JavaScript
 
A very common requirement that comes up when building a form with lot of fields is resetting the controls back to their original state. In this article, we will explore how to do this task using both ASP.NET and Javascript. I assume you know how to build web pages in asp.net 2.0.
Using ASP.NET
Step 1: Drag and drop a few controls like textboxes, radio buttons, checkboxes etc. on to the form
Step 2: Add a button to the form and rename its Text property as “Clear all controls using ASP.NET”.  Rename its id property to be “btnClearASP”.
Step 3: Double click the button. In its click event, call a method that will clear the content of the controls on a Page.
C#
protected void btnClearASP_Click(object sender, EventArgs e)
    {
        ResetFormControlValues(this);
    }
VB.NET

Protected Sub btnClearASP_Click(ByVal sender As Object, ByVal e As EventArgs)

ResetFormControlValues(Me)

 

End Sub

Step 4: Write code for this method
C#
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;
                 
                }              
            }
        }
    }
VB.NET
PrivateSub ResetFormControlValues(ByVal parent As Control)
ForEach c As Control In parent.Controls
If c.Controls.Count > 0 Then
ResetFormControlValues(c)
Else
SelectCase c.GetType().ToString()
Case"System.Web.UI.WebControls.TextBox"
CType(c, TextBox).Text = ""
Case"System.Web.UI.WebControls.CheckBox"
CType(c, CheckBox).Checked = False
Case"System.Web.UI.WebControls.RadioButton"
CType(c, RadioButton).Checked = False
EndSelect
EndIf
Next c
EndSub
The above function is a recursive function that clears the controls values on a page. I am not sure if this will work for a collection control like a RadioButtonList or similar. But I hope you have got some idea of how to write a function to reset contents on a page.
  Using Javascript
 Step 1: Drag and drop a few controls like textboxes, radio button, checkboxes etc. on to the form.
Step 2: Drag and drop a html button on the form. Rename it to “Clear All Controls Using Javascript”. Add an 'OnClick' attribute and point it to a function “ClearAllControls()” as shown below
<input id="Button1" type='button' onclick='ClearAllControls()' value='Clear All Controls Using Javascript'/>
Step 3: Write code for this function 'ClearAllControls()’. In the <head> section of the page, add a <script> tag and write the code for the function as shown below :
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Reset controls</title>
    <script language="javascript" type='text/javascript'>
 
        function ClearAllControls()
        {
              for (i=0; i<document.forms[0].length; i++)
              {
                    doc = document.forms[0].elements[i];
                    switch (doc.type)
                    {
                        case "text" :
                                doc.value = "";
                                break;
                          case "checkbox" :
                                doc.checked = false;
                                break;   
                          case "radio" :
                                doc.checked = false;
                                break;               
                          case "select-one" :
doc.options[doc.selectedIndex].selected = false;
                                break;                     
                          case "select-multiple" :
                                while (doc.selectedIndex != -1)
                                {
                                      indx = doc.selectedIndex;
                                      doc.options[indx].selected = false;
                                }
                                doc.selected = false;
                                break;
                                   
                          default :
                                break;
                    }
              }
        }
 
</script>
 
 
</head>
<body>
    <form id="form1" runat="server">
    <div>
// Other control come here
// Original Code frumbert
 
That’s it. Quiet simple, wasn’t it. I would encourage you to play with the code and add to it, by writing some of your own for the other controls on the page.
Happy coding!!
Conclusion
In this article, we saw how easy it was to reset controls on a page. If you require a specific tip, drop in a line to me at http://www.dotnetcurry.com/Contact.aspx or add your request as a comment on this page. Your comments will drive me to continue this series. I hope this article was useful and I thank you for viewing it.
If you liked the article,  Subscribe to my RSS Feed. 







Follow me on twitter

Page copy protected against web site content infringement by Copyscape


How would you rate this article?

User Feedback
Comment posted by amal on Monday, October 01, 2007 2:14 AM
good for basic tips
Comment posted by naidu on Tuesday, November 06, 2007 2:01 AM
Hi,

Thanks for the above article. But i would like to know how it  is possible to clear the value of the FileUpload control using javascript in the .aspx form. It would be a great help if i receive any suggestions from you. Thanks in advance.

naidu.
Comment posted by Suprotim Agarwal on Wednesday, November 07, 2007 11:30 PM
Dear Naidu,
To clear the FileUpload control using javascript, use the following code :

Page.RegisterClientScriptBlock("empty","document.getElementById(' " + myFileUpload.ClientID+ " ').innerText = ' ';");
Comment posted by Jaydeep on Monday, November 19, 2007 1:33 AM
When I am using the above script, one problem occurs. The validation message not gets invisible.

Comment posted by Suprotim Agarwal on Wednesday, November 21, 2007 9:03 AM
Jaydeep, which validation message are you talking about?
Comment posted by DD on Tuesday, September 02, 2008 1:27 PM
Is this different than using <input type="reset" />
Comment posted by mosser on Tuesday, September 02, 2008 6:12 PM
I think the author wanted to show how to do it on a server side button ctrl and the js example for not causing a postback. Good article!
Comment posted by amit dubey on Tuesday, September 16, 2008 5:38 AM
good...
Comment posted by amit dubey on Tuesday, September 16, 2008 5:41 AM
good...
Comment posted by Rahul on Wednesday, September 17, 2008 4:28 AM
Yes , i got the solution but this thing can be done just by single click on the "reset" button in html pages . And here the problem is totally client side not server side. so is there any solution that is suppose to be fast and efficient beside long javascript and serverside coded solution. I think i am right to ask this question. Isn't it ?
Comment posted by mosser on Wednesday, September 17, 2008 8:23 AM
I think If you do not want to use a server control, the reset button should be ok.
Comment posted by sandy on Wednesday, March 25, 2009 9:57 AM
very good site
Comment posted by DG on Friday, March 27, 2009 2:02 PM
Very helpful! Add this to the javascript and it will clear multi-line text boxes:

                case "textarea":
                    doc.value = "";
                    break;  
Comment posted by Mohit Zinzuvadia on Tuesday, September 22, 2009 10:22 AM
oh boss...thank you very much for your this code...it really helped me alot...thank you very much
Comment posted by Ratheesh.S on Tuesday, October 06, 2009 5:10 AM
Hi author Please replace document.forms[0].length with document.forms[0].elements.length otherwise it may cause and index problem :-)  

for (i=0; i<------document.forms[0].length-----; i++)
              {
                    doc = document.forms[0].elements[--i--];




Post your comment
Name:
E-mail: (Will not be displayed)
Comment:
Insert Cancel