Postbacks and Web User Control (ASCX) pages

Recently I had a problem where I was loading a web user control (ASCX) file onto a web form through a placeholder.  The actual web form had very little to it, all it did was load the web user control into the placeholder, and nothing else, all the work happened in the user control.

Whenever I did a postback from the ASCX file, I could not programatically extract any values from them, either by referencing the form objects directly (TextBox1.Text), or indirectly (PlaceHolder1.FindControl(TextBox1.Text).  In either case, the object would always be found, but it would never have its value saved, it would always be empty, regardless of whether it was a textbox, dropdown, checkbox, etc.

I tried messing around with ViewState options and scopes, but I eventually traced it back to the fact that I was loading the placeholder from the Page_Load area, rather than the OnInit() section.  Once I moved the following code:

PlaceHolder1.Controls.Add(Page.LoadControl("MyUserControl.ascx"));

from the Page_Load() area to the OnInit() area, the code worked fine.  I really should take some time to carefully read the documentation about the ASP.NET page life cycle and how it handles viewstate.  I have somewhat of an understanding of it, but problems like this stem from my ignorance about aspects of it.

Advertisements

0 Responses to “Postbacks and Web User Control (ASCX) pages”



  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s





%d bloggers like this: