Dynamic controls in ASP.NET

As many articles point out it is important to load dynamic control in the Init event of the life cycle. This is important if you want to preserve the view state.

Another thing I found out… you need to instantiate the control, add it to a ControlCollection and then set the properties of the control. If you set the properties before it is added to a ControlCollection. The view state does not work.

This is wrong

BaseProductControl control = (BaseProductControl)this.Page.LoadControl(product.ViewControl);
control.ProductId = productId;
ProductViewPlaceHolder.Controls.Add(control);

This will work

BaseProductControl control = (BaseProductControl)this.Page.LoadControl(product.ViewControl);
ProductViewPlaceHolder.Controls.Add(control);
control.ProductId = productId;

About Mikkel Ovesen

I am a .NET developer, primarily developing apps for the web. I have been working with ASP.NET and C# for more than 5 years, and web development for 10 years. I like open-source software and burgers ;)
This entry was posted in Development and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>