Question

Disclaimer: What I'm trying to do is probably so horribly wrong, feel free to provide me with an entirely different way of doing it.

Basically, I'm trying to create a UserControl that wraps up an asp Label and add some extra functionality on top for my project (e.g. some attributes that change the behaviour of the label server side). The html of the control is simple:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Label.ascx.cs" Inherits="MyNamspace.Label" %>
<asp:Label runat="server" ID="lblThis" />

and many of the properties behind it look like this:

public string Text
{
    get { return lblThis.Text; }
    set { lblThis.Text = value; }
}

I'm stuck with AssociatedControlID though, and I'm pretty sure it's because lblThis is unaware of any other control on the page, it's stuck in isolation. Ultimately I get the error "Unable to find control with id 'foo' that is associated with the Label 'lblThis'."

So my question is, is there a way to get AssociateControlID working this way, or, is there a better way of adding functionality to an asp control?

Was it helpful?

Solution 2

If all your user control has is one child control, I think you're better off creating it as a custom control instead. Those are written completely in code, so it'll get rid of the superfluous .ascx file and your AssociatedControlID will work as well.

For a tutorial, check out this:

http://msdn.microsoft.com/en-us/library/vstudio/yhzc935f(v=vs.100).aspx

Their example even happens to show how to extend a label control, which is exactly what you want. The page is a bit long but in the end it just boils down to creating a class that inherits from Label and then registering it with a <%@ Register %> or in a web.config file.

OTHER TIPS

I know this is an old question, but I was cleaning up some old web forms pages today, and came across the same problem. TBH, I was too lazy to recreate all my user controls as custom controls, so I wanted to see if it could be done without much changes.

Turns out to be quite straightforward actually. If your user control has an ID of Foo, and it contains (for example) a textbox with an ID of Bar, then the label becomes:

<asp:Label runat="server" AssociatedControlID="Foo:Bar"...>

Hope this helps someone with the same issue.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top