Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>What I have come up with so far is something like this:</p> <pre><code>public static class extenstions { private static Dictionary&lt;Type, Action&lt;Control&gt;&gt; controldefaults = new Dictionary&lt;Type, Action&lt;Control&gt;&gt;() { {typeof(TextBox), c =&gt; ((TextBox)c).Clear()}, {typeof(CheckBox), c =&gt; ((CheckBox)c).Checked = false}, {typeof(ListBox), c =&gt; ((ListBox)c).Items.Clear()}, {typeof(RadioButton), c =&gt; ((RadioButton)c).Checked = false}, {typeof(GroupBox), c =&gt; ((GroupBox)c).Controls.ClearControls()}, {typeof(Panel), c =&gt; ((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&lt;T&gt;(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); } } } } </code></pre> <p>Now you can just call the extension method ClearControls like this:</p> <pre><code> private void button1_Click(object sender, EventArgs e) { this.Controls.ClearControls(); } </code></pre> <p>EDIT: I have just added a generic ClearControls method that will clear all the controls of that type, which can be called like this:</p> <pre><code>this.Controls.ClearControls&lt;TextBox&gt;(); </code></pre> <p>At the moment it will only handle top level controls and won't dig down through groupboxes and panels.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload