简体   繁体   中英

Find controls being rendered in master page at runtime

I have a master page which has a number of controls on it both from the content page and the master page itself. All these controls extend System.Web.UI.UserControl and some implement an interface called IControlInjector.

When the master page loads, is there any way I can check in the master page what controls are being loaded in the control tree and find all those that implement the IControlInjector interface?

// put in code-behind class...
private void GatherIControlInjectors(Control control, IList<IControlInjector> controls){
     foreach(Control ctrl in control){
          if(ctrl is IControlInjector)
              controls.Add(ctrl);

          if(ctrl.Controls.Count > 0)
              GatherIControlInjectors(ctrl, controls);
     }
     return;
}


// example
IList<IControlInjector> ctrlInjectors = new List<IControlInjector>();
GatherIControlInjectors(Master, ctrlInjectors);

Instead of doing it retrospectively you could add an extension method for ControlsCollection .Add or override ControlsCollection and the add method to deal with adding controls, implementing specific interfaces, in order that you can stick them straight into a registry (for example a dictionary or list). Thereby having access to your controls in a strongly typed, quick lookup fashion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM