views:

41

answers:

2

I want to do something like this:

Panel divPanel = new Panel();
divPanel.ID = "divPanel";
this.Page.Controls.Add(divPanel);


string script = "function alertID(){alert("the id is: "+divPanel.ClientID+");}";
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "scripttests", script);

But when I put this code in page_load, I don't get the full id, which is ctl00_ContentMain_divPanel, I just get divPanel.

Is there another event I should use? How do I make this work?

A: 

PreRender is fine, however it should work in Page_Load as well.

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

Is your script rendering code running in page_load as well? They are together in your example above, but perhaps they were just copy/pasted together?

If this code is in a custom control, you also need to add the INamingContainer interface to the control declaration for ClientID to work as you expect:

http://msdn.microsoft.com/en-us/library/system.web.ui.inamingcontainer.aspx

Additionally, if this is a custom control, you should add to the Controls collection of the control itself, not the containing page. ie: this.Controls.Add() instead of this.Page.Controls.Add()

David
I tried Page_PreRender first, but it still gives me just divPanel
updated the answer with some more details
David
Thanks for your help! The example is really stripped down, the actual code is much larger. I found out that the real answer was to use the CreateChildControls event.
A: 

In your example you are adding directly to the Page controls collection. This would mean that the client id should be divPanel. Perhaps the client id you expect it to be is the incorrect one.

Daniel