views:

132

answers:

4

I have a control which is repeated several times in a page. I'd like each occurrence to have a unique ID which I will define (not the horrible ID asp.net attaches). The problem is that I will only know the ID in run time.

I'd like in the .aspx to write the following:

<uc8:MyControl ID="<%=THEID%>" runat="server" />

but I know it doesn't work. What's the right way to approach this?

Thanks a lot!

A: 

Better to add the control from code behind, add a panel and then add controls to it.

Ravia
A: 

Sadly, you're stuck with the .NET id at this time in ASP.NET 3.5. Unless you want to add the control programatically at run time, you can only Read the Id as it will appear on the client. You often have to do some client-side tricks to find the right control.

Once to make a form 508 compliant I had to analyze the pattern that .NET seemed to use to give id's to my nested controls and try to predict it. It seems to have worked for the past year; I keep my fingers crossed. Or, you can get the ClientID property at run time and write it to a hidden field, like so:

<input id='SpecialControlID' type='hidden' value='<%= SpecialControl.ClientID %>'>

Then you javascript can determine the ID. In short, there no good ways, only annoying hack ways. Easiest to add your controls at run-time.

Hope comes with VS2010, where you have options for improving this. You can change the settings for a control to use a specified ID, or to just simplify the algorithm .NET uses to determine the id, so that it is more predictable. Here's a good link.

Patrick Karcher
A: 

ASP.NET 4 has "predictable client ID's" http://www.asp.net/learn/aspnet-4-quick-hit-videos/video-8845.aspx

dev.e.loper
+1  A: 

You may add with code:

MyControl control = new MyControl();
control.ID == "myControl" + count.ToString();
ph.Controls.Add(control);

where ph - Placeholder or Panel control, count - some counter.

sashaeve