ilivewithian
ilivewithian

Reputation: 19702

Good way to handle missing AssociatedControlID

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?

Upvotes: 2

Views: 525

Answers (1)

Pavel Chuchuva
Pavel Chuchuva

Reputation: 22465

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>

Upvotes: 2

Related Questions