Looking for a client id for dynamically created controls?

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, 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 on the displayed page appears blank.

What am I missing here?

+5
source share
2 answers

You need to specify an ID control, otherwise the ID attribute will not be generated. Make changes to your C #, which looks something like this:

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

http://jagregory.com/writings/how-to-use-clientids-in-javascript-without-the-ugliness/

<script type="text/javascript">
   var txtUsernameID = '<%= txtUsername.ClientID %>';
   var txtPasswordID = '<%= txtPassword.ClientID %>';
 </script>

, , id

:

    <asp:Panel runat="server" ID="pnl"></asp:Panel>
    <script type="text/javascript">
        var txtUsernameID = '<%= myLabel.ClientID %>';

CodeBehind:

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        AddedControl();
    }

    protected Label myLabel = new Label();
    void AddedControl()
    {
        myLabel.Text = "Labelll";
        this.pnl.Controls.Add(myLabel);
    }
}

Html:

<span>Labelll</span>


<script type="text/javascript">
    var txtUsernameID = 'ctl02';   
-2

All Articles