general method to clearform in asp.net?
I am using master page with content pages. I want to write a genral me开发者_如何转开发thod to clear textboxes and for dropdownlist set index to 0. Please guide on this.
A Server-Side Approach
If you want to clear the TextBoxes and DropDownLists on postback, you could recurse through the page's Controls
collection and for each control see if it's a TextBox or DropDownList. Here's such a function in C#:
void ClearInputs(ControlCollection ctrls)
{
foreach (Control ctrl in ctrls)
{
if (ctrl is TextBox)
((TextBox)ctrl).Text = string.Empty;
else if (ctrl is DropDownList)
((DropDownList)ctrl).ClearSelection();
ClearInputs(ctrl.Controls);
}
}
To use this you'd call ClearInputs
passing in the control collection you want to search. To clear out all TextBoxes and DropDownLists on the page you'd use:
ClearInputs(Page.Controls);
A Client-Side Approach
An alternative tactic would be to use a client-side approach. Namely, use JavaScript to recurse through the DOM and clear/reset the textboxes and drop-downs on this page. The following JavaScript uses the jQuery library to simplify things:
function clearElements() {
$("input[type=text]").val('');
$("select").attr('selectedIndex', 0);
}
In a nutshell, it sets the value
of all <input type="text" ... />
elements on the page to an empty string and sets the selectedIndex
attribute of all <select>
elements on the page to 0. I've created a script on JSFiddle.net to let you try out the script: http://jsfiddle.net/xs6G9/
For More Information
I wrote a blog entry on this topic with more information and discussion. See: Resetting Form Field Values in an ASP.NET WebForm.
Happy Programming!
<input type="reset">
is a simple solution client side.
精彩评论