13

I was wondering, is there a way I can reset all the checkboxes, textboxes, numerics and other controls back to the default values without writing code for every control individually? This is the code I've tried, but doesn't seem to work:

for (int i = 0; i < this.Controls.Count; i++)
{
    this.Controls[i].ResetText();
}

EDIT:
I've fixed it by manually setting the control values, sorry for all the trouble >.<.

Yuki Kutsuya
  • 3,968
  • 11
  • 46
  • 63
  • I guess since you are just looping over the top level of controls, you have to recursively check for the controls and do a `ResetText()` (so if you have your Textbox, checkbox say within a panel then this doesn't check the controls within the panel) – V4Vendetta Mar 22 '13 at 11:56
  • @V4Vendetta I see, is there any way to make this possible? Or do I have to check through all panels and other containers? – Yuki Kutsuya Mar 22 '13 at 11:59
  • Yes, It's possible. See my answer. – ispiro Mar 22 '13 at 12:01
  • @ispiro Yea, it kinda works, but it also resets the labels :p. Trying to solve that problem atm. – Yuki Kutsuya Mar 22 '13 at 12:04
  • Well, you could just do `foreach (Control c in this.Controls) { if (c is TextBox) { c.ResetText(); } }` - _or something like that._ No need to use a **for-loop**. – Momoro May 22 '20 at 08:27

10 Answers10

17

Do as below create class and call it like this

Check : Reset all Controls (Textbox, ComboBox, CheckBox, ListBox) in a Windows Form using C#

private void button1_Click(object sender, EventArgs e)
{
   Utilities.ResetAllControls(this);
}

public class Utilities
    {
        public static void ResetAllControls(Control form)
        {
            foreach (Control control in form.Controls)
            {
                if (control is TextBox)
                {
                    TextBox textBox = (TextBox)control;
                    textBox.Text = null;
                }

                if (control is ComboBox)
                {
                    ComboBox comboBox = (ComboBox)control;
                    if (comboBox.Items.Count > 0)
                        comboBox.SelectedIndex = 0;
                }

                if (control is CheckBox)
                {
                    CheckBox checkBox = (CheckBox)control;
                    checkBox.Checked = false;
                }

                if (control is ListBox)
                {
                    ListBox listBox = (ListBox)control;
                    listBox.ClearSelected();
                }
            }
        }      
    }
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
  • This doesn't seem to work, is it because my items are in a `TabControl`? – Yuki Kutsuya Mar 22 '13 at 11:58
  • @FoxyShadoww i guess you will have to iterate through the `TabPages` then – V4Vendetta Mar 22 '13 at 12:05
  • +1 2 years on and this worked beautifully for me. I removed the `foreach` inside the method and interated at the declaration so I don't need to be particular about the Control. `foreach (Control ctrl in grp1.Controls) { Utilities.ResetAllControls(ctrl); }` – ZeroBased_IX Mar 16 '15 at 14:16
  • If I may ask, why is the parameter of type Control? Why isnt it of type Form? Shouldnt it be a form so that I can loop over all the controls that lie inside it? – Mohamed Motaz Jan 27 '20 at 22:16
15

You can create the form again and dispose the old one.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void btnReset_Click(object sender, EventArgs e)
    {
        Form1 NewForm = new Form1();           
        NewForm.Show();
        this.Dispose(false);
    }
}
Angus Chung
  • 1,547
  • 1
  • 11
  • 13
  • 3
    I know this thread is old but is there any reason I shouldn't do this? It seems to be a heck of a lot easier than any of the other answers. – VinnyGuitara Jun 08 '16 at 13:53
  • @VinnyGuitara If you're resetting *all* the items on the form, then no, there's no reason not to. If someone wanted to use an answer here to reset just part of a form, then this one would not be helpful. – TylerH Dec 21 '19 at 07:17
  • This is likely only to work in very simple cases - it created weird behaviour when I tried to use it where the form lifetime was held by a parent form. – David Lowndes Jul 19 '21 at 23:03
4
foreach (Control field in container.Controls)
            {
                if (field is TextBox)
                    ((TextBox)field).Clear();
                else if (field is ComboBox)
                    ((ComboBox)field).SelectedIndex=0;
                else
                    dgView.DataSource = null;
                    ClearAllText(field);
            }
bummi
  • 27,123
  • 14
  • 62
  • 101
3

Additional-> To clear the Child Controls The below function would clear the nested(Child) controls also, wrap up in a class.

 public static void ClearControl(Control control)
        {
            if (control is TextBox)
            {
                TextBox txtbox = (TextBox)control;
                txtbox.Text = string.Empty;
            }
            else if (control is CheckBox)
            {
                CheckBox chkbox = (CheckBox)control;
                chkbox.Checked = false;
            }
            else if (control is RadioButton)
            {
                RadioButton rdbtn = (RadioButton)control;
                rdbtn.Checked = false;
            }
            else if (control is DateTimePicker)
            {
                DateTimePicker dtp = (DateTimePicker)control;
                dtp.Value = DateTime.Now;
            }
            else if (control is ComboBox)
            {
                ComboBox cmb = (ComboBox)control;
                if (cmb.DataSource != null)
                {
                    cmb.SelectedItem = string.Empty;
                    cmb.SelectedValue = 0;
                }
            }
            ClearErrors(control);
            // repeat for combobox, listbox, checkbox and any other controls you want to clear
            if (control.HasChildren)
            {
                foreach (Control child in control.Controls)
                {
                    ClearControl(child);
                }
            }


        }
Teju MB
  • 1,333
  • 5
  • 20
  • 37
1

If you have some panels or groupboxes reset fields should be recursive.

public class Utilities
{
    public static void ResetAllControls(Control form)
    {
        foreach (Control control in form.Controls)
        {
            RecursiveResetForm(control);
        }
    }

    private void RecursiveResetForm(Control control)
    {            
        if (control.HasChildren)
        {
            foreach (Control subControl in control.Controls)
            {
                RecursiveResetForm(subControl);
            }
        }
        switch (control.GetType().Name)
        {
            case "TextBox":
                TextBox textBox = (TextBox)control;
                textBox.Text = null;
                break;

            case "ComboBox":
                ComboBox comboBox = (ComboBox)control;
                if (comboBox.Items.Count > 0)
                    comboBox.SelectedIndex = 0;
                break;

            case "CheckBox":
                CheckBox checkBox = (CheckBox)control;
                checkBox.Checked = false;
                break;

            case "ListBox":
                ListBox listBox = (ListBox)control;
                listBox.ClearSelected();
                break;

            case "NumericUpDown":
                NumericUpDown numericUpDown = (NumericUpDown)control;
                numericUpDown.Value = 0;
                break;
        }
    }        
}
  • RecursiveResetForm needs to be static as well if called statically from method ResetAllControls. Also, when resetting the ComboBox, it's likely better to set SelectedIndex to -1 as it will clear the box instead of selecting the first item as yours currently does. – Key Lay Sep 20 '19 at 21:05
0

You can reset all controls of a certain type. Something like

foreach(TextBox tb in this.Controls.OfType<TextBox>().ToArray())
{
   tb.Clear();
}

But you can't reset all controls at once

Tomtom
  • 9,087
  • 7
  • 52
  • 95
0

Quick answer, maybe it'll help:

private void button1_Click(object sender, EventArgs e)
{            
    Form2 f2 = new Form2();
    f2.ShowDialog();
    while (f2.DialogResult == DialogResult.Retry)
    {
        f2 = new Form2();
        f2.ShowDialog();
    }
}

and in Form2 (The 'settings' Form):

private void button1_Click(object sender, EventArgs e)
{
    DialogResult = DialogResult.OK;
    Close();
}

private void button2_Click(object sender, EventArgs e)
{
    DialogResult = DialogResult.Retry;
    Close();
}
ispiro
  • 26,556
  • 38
  • 136
  • 291
  • But this restarts the form doesn't it? The settings are being loaded when the form starts, so I'm not quite sure if this will work :(. – Yuki Kutsuya Mar 22 '13 at 12:11
  • @FoxyShadoww I don't understand. Yes, it will restart the Form. Isn't that what you want? (If the settings are loaded in the constructor - they will be for the new instance as well.) – ispiro Mar 22 '13 at 12:13
  • Okai, I'm going to give it a try, but the settings are being loaded from an external XML file. EDIT: Yea, this doesn't seem to work for me for some reason... – Yuki Kutsuya Mar 22 '13 at 12:14
  • @FoxyShadoww Are they loaded in the Settings-Form constructor? – ispiro Mar 22 '13 at 12:21
  • No, they are not. They are loaded on the `Form_Load` event via a `backgroundworker`. – Yuki Kutsuya Mar 22 '13 at 12:22
  • @FoxyShadoww If it's in the **settings**-Form `Form_Load` I think it should work. – ispiro Mar 22 '13 at 12:23
  • Yes the form reloads perfectly and all the changes are reverted, but it doesn't seem to load the values I set in the `Text` and `Value` properties of the controls. EDIT: I'm sorry if I weren't clear enough :(. – Yuki Kutsuya Mar 22 '13 at 12:26
0

I recently had to do this for Textboxes and Checkboxes but using JavaScript ...

How to reset textbox and checkbox controls in an ASP.net document

Here is the code ...

<script src="http://code.jquery.com/jquery-1.7.1.js" type="text/javascript"></script>

<script type="text/javascript">
      function ResetForm() {
          //get the all the Input type elements in the document
          var AllInputsElements = document.getElementsByTagName('input');
          var TotalInputs = AllInputsElements.length;

          //we have to find the checkboxes and uncheck them
          //note: <asp:checkbox renders to <input type="checkbox" after compiling, which is why we use 'input' above
          for(var i=0;i< TotalInputs ; i++ )
          {
            if(AllInputsElements[i].type =='checkbox')
            {
                AllInputsElements[i].checked = false;
            }
          }

          //reset all textbox controls
          $('input[type=text], textarea').val('');

          Page_ClientValidateReset();
          return false;
      }

      //This function resets all the validation controls so that they don't "fire" up
      //during a post-back.
      function Page_ClientValidateReset() {
          if (typeof (Page_Validators) != "undefined") {
              for (var i = 0; i < Page_Validators.length; i++) {
                  var validator = Page_Validators[i];
                  validator.isvalid = true;
                  ValidatorUpdateDisplay(validator);
              }
          }
      }
</script>

And call it with a button or any other method ...

<asp:button id="btnRESET" runat="server" onclientclick="return ResetForm();" text="RESET" width="100px"></asp:button>

If you don't use ValidationControls on your website, just remove all the code refering to it above and the call Page_ClientValidateReset();

I am sure you can expand it for any other control using the DOM. And since there is no post to the server, it's faster and no "flashing" either.

LoftyWofty
  • 87
  • 1
  • 8
0
    function setToggleInputsinPnl(pnlName) {
    var domCount = pnlName.length;
    for (var i = 0; i < domCount; i++) {
        if (pnlName[i].type == 'text') {
            pnlName[i].value = '';
        } else if (pnlName[i].type == 'select-one') {
               pnlName[i].value = '';
        }
    }
}
Alireza Masali
  • 668
  • 1
  • 10
  • 19
0

There is a very effective way to use to clear or reset Windows Form C# controls like TextBox, ComboBox, RadioButton, CheckBox, DateTimePicker etc.

private void btnClear_Click(object sender, EventArgs e)
{
    Utilities.ClearAllControls(this);
}

internal class Utilities
{
    internal static void ClearAllControls(Control control)
    {
        foreach (Control c in control.Controls)
        {
            if (c is TextBox)
            {
                ((TextBox)c).Clear();
            }
            else if (c is ComboBox)
            {
                ((ComboBox)c).SelectedIndex = -1;
            }
            else if (c is RadioButton)
            {
                ((RadioButton)c).Checked = false;
            }
            else if (c is CheckBox)
            {
                ((CheckBox)c).Checked = false;
            }
            else if (c is DateTimePicker)
            {
                ((DateTimePicker)c).Value = DateTime.Now; // or null 
            }
        }
    }
}

To accomplish this with overall user experience in c# we can use one statement to clear them. Pretty straight forward so far, above is the code.