What is the best way to clear all controls on a form C#?

前端 未结 8 2200
情书的邮戳
情书的邮戳 2020-11-27 18:00

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 wa

8条回答
  •  爱一瞬间的悲伤
    2020-11-27 18:23

    What I have come up with so far is something like this:

    public static class extenstions
    {
        private static Dictionary> controldefaults = new Dictionary>() { 
                {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(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();
    

    At the moment it will only handle top level controls and won't dig down through groupboxes and panels.

提交回复
热议问题