How to load user control dynamically in asp.net page ?


Hi

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 asp.net page like this


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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
    </div>
    </form>
</body>
</html>


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);
        PlaceHolder1.Controls.Add(featuredProduct);
    }

    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);
    }
}

Advertisement

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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.