Finding the client ID of dynamically created controls?

Matt picture Matt · Jun 18, 2011 · Viewed 9.3k times · Source

How can I find the client ID of a dynamically created control?

In my ascx, I have the following snippet.

  function DoSomething() {
        var loneStar= $find("<%= loneStar.ClientID %>");
        loneStar.hide();
    }

In my code behind, I have

public partial class SomeControl: System.Web.UI.UserControl
    {
    protected Label loneStar = new Label { Text = "Raspeberry", ForeColor = System.Drawing.Color.DarkGray};

    private void someOtherMethod()
         {
         somePanel.Controls.Add(loneStar);
         }
    }

The problem is that the ClientID in the rendered page comes up as empty.

What am I missing here?

Answer

Ender picture Ender · Jun 18, 2011

You need to give the control an ID, otherwise no ID attribute will be generated. Make a change to your c# that looks something like this:

protected Label loneStar = new Label { ID = "loneStar", Text = "Raspeberry", ForeColor = System.Drawing.Color.DarkGray};