Dynamically Loading User Controls in ASP.Net

You can dynamically load a User control at runtime and display it in a page.

You load a User control at runtime with the Page.LoadControl() method. This method returns an instance of the Control class that you can add to a page. Typically, you add the User control to a PlaceHolder control that you have declared on the page.

The PlaceHolder control was designed to do absolutely nothing. It simply acts as a placeholder on the page where you can add other controls.

<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<script runat="server">

const string CtrlFolder = "~/WebRoot";

protected void Page_Load(object sender, EventArgs e)
{
string WebRootPath = GetRandomWebPath();
Control LoadCtrl = Page.LoadControl(WebRootPath);
PHLoadControl.Controls.Add(LoadCtrl);
}

private string GetRandomWebPath()
{
Random rnd = new Random();
string[] files = Directory.GetFiles(MapPath(CtrlFolder), "*.ascx");
string WebRootPath = Path.GetFileName(files[rnd.Next(files.Length)]);
return Path.Combine(CtrlFolder, WebRootPath);
}

</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Load a User control</title>
</head>
<body>
<form id="form1" runat="server">
<div>

<asp:PlaceHolder id="PHLoadControl" Runat="server" />

</div>
</form>
</body>
</html>
Tags:
Hot on Web:


About author