views:

207

answers:

2

I have a medium sized project with a lot of pages. One of the things that I've noticed is that we have a lot of labels that have AssociatedControlID pointing to controls that are not visible. The target controls are set visible when a user has edit permissions, but not normally.

This means that the html generated in not valid, which we'd like to get as close to as possible.

I attempted to implement a new label, which overrides the existing label control and render the for attribute only when needed. This proved painful as much of the functionality required was set to internal in the Label class.

Is there a better way?

A: 

What I've done on previous projects is to simply create a custom control dervied from the TextBox control. I would add new property of something like Editable and then set it accordingly. My custom control would then override the Render like this:

public class MyTextBox : TextBox
{
    public bool Editable { get; set; }

    protected override void Render(System.Web.UI.HtmlTextWriter writer)
    {
        if (Editable)
        {
            base.Render(writer);
        }
        else
        {
            writer.Write("<span id=\"" + ClientID + "\">" + Text + "</span>");
        }
    }
}
CAbbott
+2  A: 

Subclassing Label control is not that hard:

namespace MyNamespace
{
   public class BetterLabel : Label
   {
      protected override void OnPreRender(EventArgs e)
      {
         Control control = FindControl(this.AssociatedControlID);
         if (control != null && !control.Visible)
            this.AssociatedControlID = "";

         base.OnPreRender(e);
      }
   }
}

Here's how to use BetterLabel:

<%@ Register TagPrefix="uc1" Namespace="MyNamespace"  %>
...
<uc1:BetterLabel ID="Label1" runat="server" Text="Label" AssociatedControlID="TextBox1" />
<asp:TextBox ID="TextBox1" runat="server" Visible="false"></asp:TextBox>
Pavel Chuchuva