Loading Dynamic User Controls - Issue

by Erik Lane 10. February 2005 10:40

I'm getting into dynamic user controls...nothing overly complicated but I'm stuck.

I've got 5-10 pages that have the exact same function but look different depending on a querystring value.  So my thought was to create one custom control that has all the functions and use it as my base class for the rest.

I've got one page with a Placeholder control and in that control I want to load these user controls based on said querystring value.  I'm getting the correct control to load and display like I want but when the form is submitted (using a Button WebControl) and posted back to itself it never reaches   the button's OnClick event within the user control code-behind.

I've read a few article like Scott's but I'm not sure how it apply's to my situation.  If I drop the user control on the form at design time and forgo the dynamic piece everything works as expected.

Someone learn me something.

private void Page_Load(object sender, System.EventArgs e)
{
	if(!Page.IsPostBack)
	{
		string ID = Request.QueryString["id"];
		string controlName = ID + ".ascx";
		UserControl PostDataControl = (UserControl)LoadControl(controlName);
		FormPlaceHolder.Controls.Add(PostDataControl);
	}
}

 

Tags:

Comments

David Neal
David Neal on 2/10/2005 5:55:00 PM

A couple of things.  When loading controls dynamically, you have to load them on every page request regardless of postback.  So, as a first suggestion, remove the IsPostBack check.  You can, however, use IsPostBack logic inside your user control.  Second, in order for your user control to handle postbacks properly, it's better to get your controls loaded as early as possible in the page event lifecycle.  I suggest you move your code to the OnInit() after InitializeComponent() and base.OnInit(e).

Hope this helps!

Comments are closed