Willem Odendaal

the coder's point of view

<November 2008>
SuMoTuWeThFrSa
2627282930311
2345678
9101112131415
16171819202122
23242526272829
30123456


Navigation

I Read

Subscriptions

Post Categories



DropDownList SelectedIndex in CreateChildControls

Thank you, Lutz Roeder! After two (frustrating) days I have finally solved my problem by looking at the System.Web source code using Reflector.

Here's the scenario - I have a DropDownList that gets created in a custom control's CreateChildControls method. Lets call the custom control ParentControl and the dropdown MyDDL. I tried to access MyDDL's SelectedIndex from ParentControl.CreateChildControls, but the selectedIndex was always wrong.

That I did not understand at all. When MyDDL is added to ParentControl's controls collection, the dropdown list should play catch-up. Since ParentControl's state is “Loaded“, MyDDL should load its viewstate, load its postback data and set its SelectedIndex, then call its own OnLoad method (don't know what I'm talking about? Check out this post).

The problem - LoadPostData is not part of the control's catching-up process.

MyDDL.LoadPostData is called by the web page itself. The web page has a method called ProcessPostData. This method steps through the postback data and tries to find the related controls by calling FindControl for each postback value. FindControl in turn calls EnsureChildControls. See what I'm getting at? EnsureChildControls then calls CreateChildControls (where we are trying to get MyDDL's SelectedIndex).

The important thing to note is that at this point LoadPostData has not been called on MyDDL yet! So the SelectedIndex has not been set yet.

Congrats to anyone who actually followed this. Usually I am not very good at explaining things :)

posted on Thursday, April 07, 2005 7:46 AM by willemo





Powered by Dot Net Junkies, by Telligent Systems