Monday, May 23, 2011

ASP.NET Reset button to clear form fields

As per me there is no such reset functionality provided by Asp.Net. So, I decided to research anything about possible solution. One thing what I have tried was a server-side routine such as

For Each ctrl As Control In Me.Controls
' clean up the textboxes
If TypeOf ctrl Is TextBox Then
DirectCast(ctrl, TextBox).Text = String.Empty
End If

' clean up the checkboxes
If TypeOf ctrl Is CheckBox Then
DirectCast(ctrl, CheckBox).Checked = "False"
End If

'clean up dropdown lists
If TypeOf ctrl Is DropDownList Then
DirectCast(ctrl, DropDownList).SelectedIndex = -1
DirectCast(ctrl, DropDownList).Text = String.Empty
End If
Next
This idea did not work out at all and I moved to javascript-based solution. I found 2 choices. One of them to add a code
ResetQuote.Attributes.Add("onClick", "document.forms[0].reset();return false;"). I tried and this did work out at all. therefore I choose the last possible solution. It's elegant and Front-end solution. It did not take any of server resources. here it is:
<asp:Button id="btnReset" OnClientClick="this.form.reset();return false;" runat="server" Text="Clear Form">
Magically this idea works very well. From application stand point, this is the ideal solution in a way to implement button "reset/clear form". I hope, it will work for you.

No comments:

Post a Comment