Sunday, February 20, 2011

Dynamically Load Controls to a web page

Hi folks !!!

this is something simple, and thought it will be important for all of you. recently, I had a requirement of adding various controls to a certain page according to the current type of  the user. Let's say , we have a user which can  be swap between three states. lets say ,

  • state A
  • state B
  • state C
and each state has its own properties and descriptions, So ideal decision is to develop three different usercontrols for the states, correct???
So i have developed  the three usercontrols.  Then we i have option of

  • either adding to all three usersontrols to the page and hiding it according to the state
  • Or, i would prefer adding the relevant usercontrol from the server side it self to the page and pass the page to the client.
in this scenario, i prefer to go with the second option, because of the performance and the elegance.
 // create a control
Control cntrlUCstate= new Control();
// Load that control 
 cntrlUCstate =   LoadControl("relative path of the control");
// assume that you are using an update panel.( aupAccBal is the update panel)
aupAccBal.ContentTemplateContainer.Controls.Add(cntrlUCstate); 

if you want , you can clear the control collection as well.  
aupAccBal.ContentTemplateContainer.Controls.Clear();



Thanks N enjoy!!!


No comments:

Post a Comment