查找动态创建的控件的客户端ID?

Mat*_*att 5 c# asp.net clientid

如何找到动态创建的控件的客户端ID?

在我的ascx中,我有以下代码段.

  function DoSomething() {
        var loneStar= $find("<%= loneStar.ClientID %>");
        loneStar.hide();
    }
Run Code Online (Sandbox Code Playgroud)

在我的代码背后,我有

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);
         }
    }
Run Code Online (Sandbox Code Playgroud)

问题是呈现页面中的ClientID变为空.

我在这里错过了什么?

End*_*der 7

您需要为控件提供ID,否则将不会生成ID属性.对您的c#进行更改,看起来像这样:

protected Label loneStar = new Label { ID = "loneStar", Text = "Raspeberry", ForeColor = System.Drawing.Color.DarkGray};
Run Code Online (Sandbox Code Playgroud)