locked
Resetting Form fields RRS feed

  • Question

  • User-1348799698 posted

    I posted this on my blog about resetting form fields:

    A coworker and I were working on a form and found it to be quite cumbersome to do it field by field. here is some code we found that works to reset all the fields in a form. Add more types in the case statement to reset more items:


     
    void resetField(object myObj)
        {
            RadioButtonList rl;
            string temp = myObj.GetType().ToString();
            switch (myObj.GetType().ToString())
            {
                case "System.Web.UI.WebControls.TextBox":
                    ((TextBox)myObj).Text = "";
                    break;
                case "System.Web.UI.WebControls.CheckBox":
                    ((CheckBox)myObj).Checked = false;
                    break;
                case "System.Web.UI.WebControls.RadioButtonList":
                    rl = (RadioButtonList)myObj;
                    if (rl.SelectedItem != null)
                        rl.SelectedItem.Selected = false;
                    break;
                default:
                    break;
            }
        }
    
        protected void Button1_Click(object sender, EventArgs e)
        {
            foreach (Control wc in Page.Form.Controls)
            {
                resetField(wc);
            }
        }
    
    
     
    Thursday, February 1, 2007 3:32 PM

All replies

  • User1283991206 posted

    Hi,

    please can you explain me what is the advantage to use this serverside piece of code instead of using the built-in function:
    <input type="reset" ...> ?

    Regards
    Marc Andre

    Friday, February 2, 2007 1:04 AM
  • User-1348799698 posted

    Honestly, there isn't.  The input type = reset does the job nicely.  If you want to do it after you consume the values on the server, then the code sample might come in handy (since you can't call the same behaivior as the html reset through server code).  Or do you have a solution for that too?

     

     

    Tuesday, February 6, 2007 8:35 AM
  • User1283991206 posted
    Ok, in this case when you need to consume the values on the serverside before you clear all data the method is helpful. Thanks for your explanation.
    Tuesday, February 6, 2007 12:11 PM
  • User-1323558006 posted
    ResetFields(Page.Controls);


    this article's very good

    http://imak47.wordpress.com/2008/08/01/how-to-reset-all-fields-of-a-web-form-in-asp-net/

    it's possible to add other controls like:

     (...)

                    case "CascadingDropDown":
                        AjaxControlToolkit.CascadingDropDown cdd = (AjaxControlToolkit.CascadingDropDown)contl;
                        cdd.SelectedValue = null;
                    break;
    (...)
     
    and the function can be called like this: 
     

     ResetFields(Page.Controls);

    Friday, October 16, 2009 11:58 AM