Thursday, August 23, 2007

Loading Controls Dynamically problem on ASP.Net 2.0

Hi Folks,

If you load your controls dynamically on asp.net 2.0 web site,you will face a problem that all handlers of server side controls doesn't work and not fire on the server side.

Even you try to put a break point on your server side handler,it will not fire,this is not because of a problem on any of your user controls or your code has something wrong.

the problem is : if you try to write the same line of code on asp.net 1.1 web application this problem will not happen at all,and if you tru to load the same controls on asp.net 2.0 web site the problem will happen.

The solution and Tip for this problem,is to just give an ID for your user control which will be loaded dyamiccly,and the problem will not happen.

This the code which run on asp.net 1.1 perfectly and doesnt run on asp.net website :

C#:
PlaceHolderID.Controls.Clear();
Control c = Page.LoadControl(”UCPath”);
PlaceHolderID.Controls.Add(c);


The Solution :
C#
PlaceHolderID.Controls.Clear();
Control c = Page.LoadControl(”UCPat”);
c.ID = “IDForYourControl“;
PlaceHolderID.Controls.Add(c);


Hope this helps.

Read more on the problem and the solution on Scott Blog :
http://scottonwriting.net/sowblog/posts/3962.aspx







Regards,
Moustafa arafa

3 comments:

Faizal said...

Mustafa,

Good Tip...

Are you seeing any performance issues with this approach of dynamically creating user control. I believe you will need to recreate this control for each postback right?


Thanks..

Moustafa El-Zoughby said...

Hi Faizal,

No performance issue you will face for loading your controls dynamically,since you will load only the control which you want to display on your page only.
This technique is not easy to implement because you have to design your controls and your project in a way tp be modular.

I used this way on all my projects and i get used to do it :).

for each post back oyu will just load the control which you want only.

Hope my reply helps you.

Feel free to ping me for any help.

Faizal said...

Thanks.

Here is a quick recap of our UI framework using additional tools ASP.NET AJAX, Ajax Tool Kit and Infragistics.

Main default page has three different update panels, two for displaying menu and one panel for displaying pages. WHen a user click on the menu each page (dynamically loaded1 user control) is loaded using Async POstback. However we are seeing an exponential decrease in the performance.

How does the asp.net runtime manages dynamically created controls? Does it do a good job in managing the memory resources (in this case when switching between different pages means user controls)?