开发者

Highlighting all user controls in an ASP.NET page

I want to highlight all user controls used in a page by adding a border around it. We are doing this to facilitate debugging. I could override RenderControl开发者_如何学C method in user control base class to do that easily but we have lot of user controls(legacy) that are not using base class.

I then took a different approach. I tried traversing page controls in PreRender method of page base class, which is used by all pages, and add a div with border to all user controls. But I found that it is not possible to add or remove from control collection if it contains code blocks (i.e. <% ... %>).

Any suggestions?

thanks


Here is how you can highlight an active input control that has the focus. You need to handle the onfocus and onblur client-side events of the input controls.and apply or remove the css style to the control by setting the controls className attribute

Add this to your css file:

.highlight
{
  background-color: #fefbd2; /*highlight with yellow*/
  color: #000080;            /*make text blue*/
}

In your App_Code directory create a helper class like

public static class Helpers
{
  /// <summary>
  /// Adds the onfocus and onblur attributes to all input controls found in the specified parent,
  /// to change their apperance with the control has the focus
  /// </summary>
  public static void SetInputControlsHighlight(Control container, string className, bool onlyTextBoxes)
  {
   foreach (Control ctl in container.Controls)
   {
     if ((onlyTextBoxes && ctl is TextBox) ||
          (!onlyTextBoxes && (ctl is TextBox || ctl is DropDownList ||
          ctl is ListBox || ctl is CheckBox || ctl is RadioButton ||
          ctl is RadioButtonList || ctl is CheckBoxList))) 
     {
        WebControl wctl = ctl as WebControl;
        wctl.Attributes.Add("onfocus", string.Format("this.className = '{0}';", className));
        wctl.Attributes.Add("onblur", "this.className = '';");
     }
     else
     {
        if (ctl.Controls.Count > 0)
           SetInputControlsHighlight(ctl, className, onlyTextBoxes);
     }
   }
  }
}

Then just override the OnLoad method of any page.

protected override void OnLoad(EventArgs e)
{
  Helpers.SetInputControlsHighlight(this, "highlight", false);
  base.OnLoad(e);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜