Finding Controls in AP.NET

One thing I really hate is duplicate code, so when I find myself writing the same code over and over, for example setting properties to the same values on one to many controls, I know there has to be an easier way. Of course there is! Why not find all the controls on a Web Form or Win Form and just set them in a loop? This prevents errors and allows greater consistency.

For example, if you forget to set the MinimumValue on a RangeValidator control, your ASP.NET page won’t load.

Here is some simple code using LINQ  to find controls that you are searching for on an ASP.NET page:

private ReadOnlyCollection<T> FindControls<T>(Control parent,
                                               bool includeChildren) 
                                               where T : Control
  if (parent == null)
    throw new ArgumentNullException("parent");
  List<T> ctrls = new List<T>(parent.Controls.OfType<T>());
  foreach (var ctrl in parent.Controls.Cast<Control>().Where(
                                         p=>p.HasControls() &
    ctrls.AddRange(FindControls<T>(ctrl, includeChildren));
  return new ReadOnlyCollection<T>(ctrls);

This code works exactly the same for Windows controls except you will have to change p.HasControls() to p.HasChildren().

Here is how I use it in a real-work example:

foreach (var ctrl in this.FindControls<RangeValidator>(parent, true))
  if (string.IsNullOrEmpty(ctrl.ErrorMessage))
    ctrl.ErrorMessage = "Input is not valid number.";
  if (string.IsNullOrEmpty(ctrl.MinimumValue))
    ctrl.MinimumValue = "0";
 if (string.IsNullOrEmpty(ctrl.MaximumValue))
    ctrl.MaximumValue = int.MaxValue.ToString();

This code originally came from my open source project located at: Related to the FindControls method above there is also:

  • ClearControls
  • SelectFirstEmptyControl
  • FindEditableControls

Tip By: David McCarter

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s