Dynamically create multiple web user controls and use them on a page
Dynamically create multiple web user controls and use them on a page
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
- 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.
LoadControl
function of Page
Class.
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";
objCtrl.Visible=false;
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.
((UserControl_MyWebUserControl)(objCtrl)).CustomProperty="Value";
Here my control class name is "UserControl_MyWebUserControl
" and I have exposed a property in that with name "CustomProperty
".
After setting all the required properties, we need to add this control object to control collection of parent control (panel in our case):
pnlControlContainer.Controls.Add(objCtrl);
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 "MyControl1
" 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;
}