How to load the user control dynamically?

Posted by in ASP.NET category on for Intermediate level | Points: 250 | Views : 10393 red flag

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).


<%@ Control Language="C#" AutoEventWireup="true" CodeFile="MenuControl.ascx.cs"

Inherits="MenuControl" %>

<div style="background-color:#f0f0f0;padding:5px;">

<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>

<hr /></div>



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="LoadUserControl.aspx.cs"

Inherits="LoadUserControl" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"



<html xmlns="">

<head runat="server">




<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.

Page copy protected against web site content infringement by Copyscape

About the Author

Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan

Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on | |

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)