Wednesday, October 06, 2004
« Sky Captain Rocks | Main | Rob Howard in Town! »

I have found it's a lot easier to blog about solutions to problems because of the turmoil and heartache involved as well as the victorious feeling of relief when the issue has been resolved.  In an attempt to be more proactive to coding solutions, rather than reactive, I will work on providing more valuable blog entries not so much about problems overcome, but techniques and strategies that I employ in my day-to-day programming because I feel that some of that experience would be valuable to someone out there in the wild wild web.

Today's blog entry, however, is not one of those blog entries.  I'm going to talk about a problem solved.  I was taught a very valuable lesson today - again.  Here's the deal:

I am working on an ASP.NET application that dynamically loads various controls depending on the user's context with the application.  Some of the controls I wrote as Server Controls while others are User Controls.  Within a particular user control (.ascx) I had placed some hidden controls (HtmlInputHidden) that provide UI feedback to the server so I can take appropriate action.

When the form was posting back to the server I couldn't see the values within the controls.  That is, the .Value property would ALWAYS return the default value (at least it would return the value assigned in the <input /> tag).  No matter what I did.  Interestingly, however, I could SET the value and that would get posted back to the server.  The only way I could ascertain this was to inspect the form's posted values - indeed the correct value was always there, but it was never associated with the control variable.

As it turns out, and it is with much embarrassment that I even admit this, I was loading the control too late in the hosting page's lifecycle.  I had the call to LoadControl(”...ascx”) in the OnLoad() method.  Instead, it belongs in the OnInit() method andthat's because the ViewState is loaded back in the controls after the OnInit and before OnLoad.  I don't know how I overlooked that, but I did.  I don't think I'm going to forget that lesson ever again.

In order to properly associate control values, property values, events, etc with dynamically loaded user controls, you must always instantiate the control in the OnInit() method (or the Page_Init() event) and add it to the parent control's .Controls collection therein:

protected override void OnInit(EventArgs e) {
   MyControl ctl = (MyControl)LoadControl(”MyControl.ascx”);
   Page.Controls.Add(ctl);
}

Wednesday, October 06, 2004 7:56:00 PM (Mountain Standard Time, UTC-07:00)  #    Disclaimer  |  Comments [0]  |  Trackback
Comments are closed.