本文介绍了什么是清除表单C#的所有控件的最好方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不记得看​​到有人问东西沿着这些路线前一段时间,但我做了搜索,但没有找到任何东西。

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).

您会如何呢?

推荐答案

我已经想出到目前为止是这样的:

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);
           }
        }

    }

}

现在你可以直接调用扩展方法ClearControls是这样的:

Now you can just call the extension method ClearControls like this:

 private void button1_Click(object sender, EventArgs e)
    {
        this.Controls.ClearControls();
    }

编辑:我只是增加了一个通用的ClearControls方法,将清除类型,可以这样调用的所有控件:

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>();

目前,它只能处理顶级的控制,并通过groupboxes和面板不会往下挖。

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

这篇关于什么是清除表单C#的所有控件的最好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 19:19