Matthew Scharley
Matthew Scharley

Reputation: 132454

How to determine ASP.NET's generated ID's from codebehind?

In ASP.NET, when you give a tag an ID it generates a unique HTML id for the element based on the control hierachy, ie.

<asp:Panel ID="test" runat="server">
    ...
</asp:Panel>
<!-- Becomes... -->
<div id="plc_lt_zoneContent_PagePlaceholder_PagePlaceholder_lt_test_test">
    ...
</div>

Is there some way of determining the generated id in the codebehind file? I need to generate some Javascript that uses the id.

Upvotes: 3

Views: 3537

Answers (3)

WIRN
WIRN

Reputation: 947

Or use ClientIDMode="Static" on the asp.net-element

Upvotes: 0

Keltex
Keltex

Reputation: 26436

Do this in javascript:

<script type="text/javascript">

  var theID = '<%= test.ClientID %>';
  // theID contains your ID

</script>

Update: I noticed a comment below that ClientId didn't work. It's ClientID (case sensitive). Here's the documentation reference to ClientID:

http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientid(VS.71).aspx

Upvotes: 10

Dean Harding
Dean Harding

Reputation: 72668

You can use the ClientID property, but it is only available from the PreRender event (or later).

ASP.NET 4 is going to make some changes to this so that you can get "predicatable" identifiers, but even then it's not a panacea.

Upvotes: 1

Related Questions