I do remember seeing someone ask something along these lines a while ago but I did a search and couldn't find anything.
I'm trying to come up with the cleanest way to clear all the controls on a form back to their defaults (e.g., clear textboxes, uncheck checkboxes).
How would you go about this?
What I have come up with so far is something like this:
public static class extenstions
{
private static Dictionary<Type, Action<Control>> controldefaults = new Dictionary<Type, Action<Control>>() {
{typeof(TextBox), c => ((TextBox)c).Clear()},
{typeof(CheckBox), c => ((CheckBox)c).Checked = false},
{typeof(ListBox), c => ((ListBox)c).Items.Clear()},
{typeof(RadioButton), c => ((RadioButton)c).Checked = false},
{typeof(GroupBox), c => ((GroupBox)c).Controls.ClearControls()},
{typeof(Panel), c => ((Panel)c).Controls.ClearControls()}
};
private static void FindAndInvoke(Type type, Control control)
{
if (controldefaults.ContainsKey(type)) {
controldefaults[type].Invoke(control);
}
}
public static void ClearControls(this Control.ControlCollection controls)
{
foreach (Control control in controls)
{
FindAndInvoke(control.GetType(), control);
}
}
public static void ClearControls<T>(this Control.ControlCollection controls) where T : class
{
if (!controldefaults.ContainsKey(typeof(T))) return;
foreach (Control control in controls)
{
if (control.GetType().Equals(typeof(T)))
{
FindAndInvoke(typeof(T), control);
}
}
}
}
Now you can just call the extension method ClearControls like this:
private void button1_Click(object sender, EventArgs e)
{
this.Controls.ClearControls();
}
EDIT: I have just added a generic ClearControls method that will clear all the controls of that type, which can be called like this:
this.Controls.ClearControls<TextBox>();
At the moment it will only handle top level controls and won't dig down through groupboxes and panels.
I know its an old question but just my 2 cents in. This is a helper class I use for form clearing.
using System;
using System.Windows.Forms;
namespace FormClearing
{
class Helper
{
public static void ClearFormControls(Form form)
{
foreach (Control control in form.Controls)
{
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;
}
}
}
}
}
And I call the method from any form like this passing a form object as a parameter.
Helper.ClearFormControls(this);
You can extend it for other types of controls. You just have to cast it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With