We generally create web user controls when we need to user same group of controls and appearance in multiple pages.
We simply register the control in page and use that like any other control. However there are situations when we can't decide it during design-time whether we need this control or not and conditionally during run-time we may need to show a web user control.
This tip is for the same purpose
Adding a web user control on a page in run-time.
- To Add web user control on a page in run-time.
- To Access the properties (control and custom) of such user control in run-time.
- To Search and access this dynamically added control.
First we need a container which can contain another control.
We can add controls to page itself however for better placement we can add a container at the appropriate location and then add controls dynamically into this per your requirements and conditions. Here we will take panel
] for this purpose.
Generally when we want to add a control in run-time, we just create an object of that class, set the properties and add that control to control collection of container.
However in case of web user control, this approach will not work and will give us null reference exception if we try to access properties exposed by web user control.
For web user control, we need to first load it in page through
Control objCtrl = Page.LoadControl("UserControl/MyWebUserControl.ascx");
Now we have loaded the control in our page, we need to set properties for this.
Accessing properties of dynamically added web user control
We can directly set the generic control properties like ID or visibility.
objCtrl.ID = "MyControl1";
However if we have any custom property exposed in web user control, it won't list in intellisense, for that we need to typecast this control object with the class of web user control.
Here my control class name is "
" and I have exposed a property in that with name "
After setting all the required properties, we need to add this control object to control collection of parent control (panel in our case):
We are done with dynamically adding web user control on our page. This was all done at declaration time, now we can have a requirement to access and manipulate this control later in code.
Searching and Accessing dynamically added web user control in run-time.
We know the parent control, we can access our web user control based on its index in control collection of parent control however using ID is the best practice (we have already set the ID "
" for our control).
Searching for control and using it.
if (pnlControlContainer.FindControl("MyControl1") != null)
UserControl_MyWebUserControl objControl = ((UserControl_MyWebUserControl)pnlCouponArea.FindControl("MyControl1"));
objControl.Visible = true;