Loading User Control Dynamically
Is it possible to dynamically load a user control in the code-behind file of a client .aspx page or must it be loaded in the .ascx file?
I tried using the code-behind file but was not successful.
Also, is it possible to have more than 1 instance of the same user control on the same page, 1 created during design time and the other loaded dynamically?
I tried that but only get 1 user control in run time.
If any of you have the solution to the above, would be a great help if you could kindly take some of your time to type in your solution.
Thank you in advance.
Control c1 = Page.LoadControl("controls/mycontrol.ascx");
2) Yes it is possible. Not sure how you tried, considering in #1 you said you didn't know how to load it dynamically
Let me know if you have problems.
In fact I did what you wrote, below is my codes in the code-behind file:
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
Dim uc2 As Control
uc2 = Page.LoadControl("SimpleCalculator.ascx")
This user control has 3 text boxes and 1 button. I received an error that says (when I dynamically loaded it using code-behind file:
"Control '_ctl0_Op1' of type 'TextBox' must be placed inside a form tag with runat=server."
The language I am using is Visual Basic.
Everything is working fine if I create an instance of the user control by drag-and-drop in design time.
Thanks for your time and help.
I managed to solve the problem.
It is because I didn't do the following:
- specify the classname attribute of the @Control directive in the .ascx file
- Use the @Reference directive to reference the user control in my web page.
After doing the above, I was able to create my user control dynamically in the code-behind file.
Loading user controls dynamically
Here is an example for your question. It's useful for you and others.
The user controls in the system are loaded dynamically. so the layout of the page can be changed while the system is running.
-- Android Development Center
-- Cloud Development Project Center
-- HTML5 Development Center
-- Windows Mobile Development Center