Asp.net web Control Enable 属性设置

最近手上有一个很简单的一个小项目,需要查看编辑的历史记录,先前设计的时候把数据都save 到DB了,现在时间紧迫 就不在画新的UI,而是采用以前的edit页面 来显示数据,这里就需要把页面上所有的control都设置为disable。而一般的control是没有Enable属性,只有WebControl才有这个属性。所以默认我们会检查当前的control是否是webcontrol,如果是直接设置enable属性,如果不是我们可以通过反射来查找,这里测试了以下,满足我页面的需求,主要代码实现如下:

  public static class ExtendClass
    {
        public static void SetEnable(this Control ctrl, bool value, Func<Control, bool> fun)
        {

            bool ret = true;
            if (fun != null)
            {
                ret = fun(ctrl);
            }
            if (ret)
            {
                if (typeof(WebControl).IsAssignableFrom(ctrl.GetType()))
                {
                    ((WebControl)ctrl).Enabled = value;
                }
                else
                {
                    PropertyInfo property = ctrl.GetType().GetProperty("Enabled");
                    if (property != null)
                    {
                        property.SetValue(ctrl, value, null);
                    }
                }
            }

            foreach (Control item in ctrl.Controls)
            {
                SetEnable(item, value, fun);
            }

        }
     
    }

测试结果如图:

原文地址:https://www.cnblogs.com/majiang/p/3647128.html