栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

清除表单C#上所有控件的最佳方法是什么?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

清除表单C#上所有控件的最佳方法是什么?

到目前为止,我想到的是这样的:

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:

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

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

this.Controls.ClearControls<TextBox>();

目前,它将仅处理顶级控件,而不会深入研究组框和面板。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/568417.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号