Dynamically Loading User Controls
In this article we are going to see how we can Load User Controls dynamically into a web page. Loading dynamically a usercontrol is useful when you want to add multiple instances of usercontrol at runtime.
In this article we are going to see how we can Load User Controls dynamically into a web page. Loading dynamically a usercontrol is useful when you want to add multiple instances of usercontrol at runtime.
To load a user control dynamically we use LoadControl method of the Page Class. This method takes two parameters:
1.The name of the user control.
2.Path to the file that contains the usercontrol definition. LoadControl method returns a referene to the control it creates.
Create a new Website and Add a User Control to the website. Right click the website and Select Add New Item -> Select Web User Control and Name it as "WebUserControl.ascx".
Now add a label control to the usercontrol as shown below:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>
<asp:Label runat="server" ID="lblMessage" Text="Welcome"></asp:Label>
Add the below property to the usercontrol which assigns value to the Text property of the label when you set some value to it and returns the value of the Label Text when called.
public string Message
{
get { return lblMessage.Text; }
set { lblMessage.Text = value; }
}
Add a new web page to the site. and in the code-behind of the web form add the below code in Page_Load event.
protected void Page_Load(object sender, EventArgs e)
{
WebUserControl uc = WebUserControl)LoadControl("WebUserControl.ascx");
WebUserControl uc1 = (WebUserControl)LoadControl("WebUserControl.ascx");
form1.Controls.Add(uc);
uc.Message = "Welcome ";
form1.Controls.Add(uc1);
uc1.Message = "Guest !!!";
}
In the above code we are dynamically creating 2 instances of the usercontrol. Then add this usercontrol instances to the Controls collection of the web form(form1). We are then assiging a value to the Message property of the usercontrol. This Message property in turn sets the value of the Label in the text box.
Above code gives an error as shown below because the control is not yet registered in the webpage.
Add the below tag in .aspx page of the webform. this registers the usercontrol with the webpage.
<%@ Register Src="~/WebUserControl.ascx" TagPrefix="uc" TagName="uc" %>
Now run the site and you will see the webpage which renders 2 usercontrols with different data.