Extension Method

Written by Adit Shah on September 07, 2016

Extension Method_image

Its a very frequent requirement that we have to enable/disable or hide a control based on some business logic. In one particular case, it had to be configurable by administrator as part of security and general administrative control of the site. This implied that it had to work with all the controls on the page with which user can interact and even some labels.
The controls had to be disabled according to configuration but we found out that not all webcontrols can be disabled. Surprisingly a label can be enabled and a hidden field has a visible property. It was decided that those which could not be disabled had to be made invisible.
I needed a way to disable or hide (depending on what was allowed) controls based on a condition. While this could have been as easily done in a loop with an if else block, this seems much easier to read and write. Fortunately Disable property is not used by Web Controls.


    public static void Disable(this Control c)
        Type t = c.GetType();
        PropertyInfo p = t.GetProperty(“Enabled”);
        if (p == null)
            PropertyInfo p1 = t.GetProperty(“Visible”);
            p1.SetValue(c, false, null);
            p.SetValue(c, false, null);

Label.Disable() would disable the label and
HiddenField.Disable() would make it invisible!!.

Kaira Software is Leading ASP.Net web Development, web development Company in India.

Leave a Reply

Your email address will not be published. Required fields are marked *

Captcha *