Enable/Disable Controls using ControlCollection

In a role based application, it is often required that certain controls on the UI form be enabled and disabled based on user’s security credentials.And the easiest way to implement such functionality in a web application is to utilize the ControlCollection that is accessible on every page.

Like their WinForm counterparts, controls on a webform can be and often is hierarchical and thus requires recursion to traverse all the controls. But unlike WinForm controls, web controls do not uniformly share the Enabled property. This means that we would have to cast each control back to their own types before we could set their Enabled property. But in reality, this should not be a big concern as there are only a few primitive types of controls that are editable.

The following code snippet shows how to achieve this in C# (here we set the TextBox and Button controls to be disabled): 

    protected void Page_Load(object sender, EventArgs e)
    {
        SetControlStatus(Controls, false); //disabled
    }
 
    public void SetControlStatus(ControlCollection col, bool enabled)
    {
        foreach (Control c in col)
        {
            ChangeContolStatus(c, enabled);
            SetControlStatus(c.Controls, enabled);
        }
    }
 
    private void ChangeContolStatus(Control c, bool enabled)
    {
        if (c is TextBox)
        {
            (c as TextBox).Enabled = enabled;
        }
        else if (c is Button)
        {
            (c as Button).Enabled = enabled;
        }
    }

In ASP.Net 2.0 and above, this code can be placed within the MasterPage and thus makes enabling and disabling controls at runtime even more trivial.

Be Sociable, Share!

Leave a Reply