Postpone CreateChildControls on Postback

February 22, 2009 23:28 by Rob

Let me explain the problem. A have a server control that really needs to serious context before it can render or process postback events. The context is set using a public property mysteriously called TypeToShow. The value of the property is a complex structure and cannot be persisted in ViewState. This all works fine when I do the initial load of the page, because the CreateChildControls of the control does not occur until I call DataBind() from the containing page.

However, when a postback occurs, the CreateChildControls() method is invoked before I get a chance to inject the meta data.

I know that Asp.Net delayes all events with child controls that are dynamically added using Controls.Add(…), so my work-around was to actually use a Placeholder and create the control until Page_Load was invoked.

There is a workaround, and here it is.:

First, you need to add a couple of statements to the beginning of CreateChildControls like so:

image

This will case CreateChildControls to fail if the property ‘_typeToShow’ was not set. Note that in my case, my control inherits from the 2.0 CompositeDataBoundControl class that does not require you to override CreateChildControls to create your controls. Instead you need to override an overload of this method. Check the SDK on the CompositeDataBoundControl for more info.

Next, you need to give the framework another chance to fire any events. The framework calls OnLoad of the child controls after the parent has been created. This includes Page_Load. To do this, override the OnLoad of the server control like so:

image

The framework detects that the controls have been created and starts raising any events you may have defined.

PS. I don’t know I anyone is reading this blog (except GoogleBot). Gimme a comment!


Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:
Categories: C# | ASP.Net | Tricks of the Trade
Actions: E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed