How to load user control dynamically in page ?


So many time we get scenario to display some user control on some location on some condition then we can achieve this by loading the user control dynamically.

For doing this task we can do like

Step 1: Create some list of user control and keep in some folder

Step2: Keep one place Holder control in page like this

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DynamicLoadingUserControl.aspx.cs" Inherits="DynamicLoadingUserControl" %>

<!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"></asp:PlaceHolder>

Step 3: Now write the code behind file of aspx page for loading the user control like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class DynamicLoadingUserControl : System.Web.UI.Page
    // randomFolder is the Folder Name which Contains the collection of User control
    const string randomFolder = "TestUserControl";

    protected void Page_Load(object sender, EventArgs e)
        string featuredProductPath = GetRandomProductPath();
        Control featuredProduct = Page.LoadControl(featuredProductPath);

    private string GetRandomProductPath()
        Random rnd = new Random();
        string[] files = Directory.GetFiles(MapPath(randomFolder), "*.ascx");
        string featuredProductPath = Path.GetFileName(files[rnd.Next(files.Length)]);
        return Path.Combine(randomFolder, featuredProductPath);


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.