Tuesday, September 21, 2004

ClientID is not reliable in CreateChildControls in ASP.Net

Here is a tip that will save you a few hours of digging. I made a composite control and instanciated my inner controls in

createChildControls. Something like this:

createChildControls()

{

t = new TextBox();

img = new Image();

Controls.Add(t);

Controls.Add(img);

// Make some javascript using ClientId like this…

….. t.ClientId …..

}

If you do it this way, your control may work fine in some pages and not in some others. This depends on how nested your

control is. Of course, you would think that the INamingContainer interface would take care of all this and give you a reliable way of getting

the client ID regardless how deep you are in the control hierarchy. After all, my textbox and Image are part of the hierarchy already since

I use ClientID after these inner controls have been added to the Control collection…

Well, this is not true to my uttermost surprise and disappointment. To cut the story short, here is the fix. The control hierarchy is

settled just before the rendering so you should always use ClientID in the prerender. So you do it like this

protected override void OnPreRender(EventArgs e)

{

// use ClientId here

}

This works fine. My googling did not reveal a real source of explanation on why this is but people have had the same problem.

I would be interested to find out a true M$ explanation for this.

No comments: