Dynamically Loading Controls

Recently, i ran into a situation where i needed to daisy-chain several usercontrols together. The basic thought was similar to most sites "New User Data Entry" forms. You fill one out, and then you goto the next one to fill more incriminating information and then the last form you fill out, you basically sign your life away and your first born.

Problem i ran into was the fact that i could not achieve this effect without a severe overload of page resources (i.e. Multi-View/View relationship) and even then it was sadly sketchy and buggy.

After doing some research and some serious code management (thats what i call it :> ) I managed to achieve a relatively small method, through VB but should be easily translatable since it is small, to get the effect i needed.

1:  Friend Shared Sub NextForm(ByRef par As Control, ByRef curr As Control, ByVal [new] As String)  
2:   'remove current control (curr) from parent (par)  
3:   par.Controls.Remove(curr)  
4:   'load control into cntrl object  
5:   Dim cntrl As Control = par.Page.LoadControl([new])  
6:   'add control to the parent  
7:   par.Controls.Add(cntrl)  
8:  End Sub  


Minus the comments and method declaration, this is a 3-liner. For my instance i put it in the residing page and as i performed my logic inside the usercontrols i simply called the page class and then the method.

Below is an example of how i used it in the code.

1:  Data.NextForm(Me.Parent, Me, "content/" & ProdType.Material.ToString & ".ascx")  

- Data is the ASPX page - Me.Parent is the usercontrols containing control (for my instance, it was a placeholder) - Me is the usercontrol - "content/" & ProdType.Material.ToString & ".ascx" is the string representation of the location of the usercontrol. If i remember right LoadControl can any of the different url representations. I use a referential level, for portability if i am lucky and it needs to be implemented elsewhere.

Comments

Popular posts from this blog

SysInternals - BgInfo for ALL Users

JSON/AJAX Helpers

Acquiring List of controls - Classic JS