In this article, we shall learn how to load the user control dynamically.
As per MSDN, A user control is a kind of composite control that works much like an ASP.NET Web page—you can add existing Web server controls and markup to a user control, and define properties and methods for the control. You can then embed them in ASP.NET Web pages, where they act as a unit.
In this article, let us learn how to load user control dynamically based on certain condition on the page.
Get hundreds of .NET Tips and Tricks here, you can also get online ASP.NET training here.
Lets assume that we have following code in ascx file (user control file).
ASCX PAGE (USER CONTROL)
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="MenuControl.ascx.cs"
<a href="Default.aspx" title="Home">Home</a> | <a href="Page1.aspx" title="Page 1">Page
1</a> | <a href="Page2.aspx" title="Page 2">Page 2</a>
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="LoadUserControl.aspx.cs"
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<form id="form1" runat="server">
<asp:PlaceHolder ID="PlaceHolder1" runat="server" />
protected void Page_Load(object sender, EventArgs e)
Control ctrl = this.Page.LoadControl("~/MenuControl.ascx");
In the above code snippet, we have a User control (MenuControl.ascx). On the .aspx page we have a
asp:PlaceHolder control that is used to hold the User control.
In the code behind of the page, we are using this.Page.LoadControl method to load the user control by passing the path of the user control and then adding this control into the asp:Placeholder.
In this way, the user control is loaded and placed on the .aspx page. The same can be applied on the master page as well.
This is useful particularly in the scenario where you need to load different user control based on different conditions.
Hope this article will be useful for the readers. Thanks for reading and keep reading forthcoming articles.