Monday, 15 October 2007

Enabling or Disabling All controls in an ASP.NET Page using Reflection

Every ASP.NET developer should know that the “Enabled” property doesn’t exist in the base System.Web.UI.Control class. Consequently, it makes it a little difficult looping through the controls collection because then you have to cast each control into its relevant type e.g. "(Button)myControlName" to be able to change this property. Typically, you would have code like this:

if (control.GetType() == typeof(Button))
Button button = (Button)control;
button.Visible = (bool)item.IsVisible;
button.Enabled = (bool)item.IsEnabled;
else if (control.GetType == typeof(TextBox))
TextBox textBox = (TextBox)control;
textBox.Visible = (bool)item.IsVisible;
textBox.Enabled = (bool)item.IsEnabled;

.... (n number times) for each and every required control type. This solution above could have 100s of lines for all the control types that require support.

See a simplified and more elegant alternative below that I came up with, using reflection - it ends up with just 2 lines rather than 10s or hundreds as seen in the previous approach...

/// Populate the secured items listing, and apply visible/disabled properties on each.
public void SecureControls()
ManagerContext db = new ManagerContext();

//Grab list of controls for current page
Control contentControl = this.Master.FindControl("BodyPlaceHolder");
List securedItems = db.Manager.SecuredItem.GetSecuredItemByPageName(this.PageName);
Control control = null;

//Set visible and enabled property; enabled property set based on reflection to control type
foreach (SecuredItem item in securedItems)
control = contentControl.FindControl(item.ControlName);
control.Visible = (bool)item.IsVisible;

if (control.GetType().GetProperty("Enabled") != null)
control.GetType().GetProperty("Enabled").SetValue(control,(bool)item.IsEnabled,null) ;


Another alternative to this approach is to custom controls with a standard interface e.g. ISecuredItem but this requires more work because all controls have to have a custom implementation.

No comments: