Dynamically Add ASP.NET User Control

Most tutorials out there show how to add an ASP.NET custom User Control (.ascx) control to a page's control list by either dragging and dropping it onto the page or putting the control's HTML onto the HTML source view. But what if you are building a dynamic control list such as for a Panel or GridView or Repeater object and need to automatically create an instance of the User Control on the fly?

Specifically, this is an issue if you have put your User Controls in the same project as your web project. If they are in a satellite assembly, then it is really easy to create an instance and use them. But from your own web project where the controls reside, it is actually possible but may not be completely obvious.



First, add a new web user control to your web project. (NOTE: This is the option called Web User Control on the new item dialog.) Call it something like: MyTestControl.ascx.

Add some text to the HTML view of the control so we know it is working when we run our code. So your HTML view of the control should look something like this:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="MyTestControl.ascx.cs" Inherits="webcontrols_MyTestControl" %>
<asp:Label ID="lblTitle" runat="server">Hello, this is my control!</asp:Label>

Now, to use the control, add a new page to your site. Call it something like:
Test.aspx.

Open the new file to the HTML view and add a Panel control so we can add our web user control to it. Make sure to not the second line where you add page reference to your control. If you don't do this, your page will not be able to recognize the web control in the code behind. Your HTML view should look something like this:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test" %>
<!-- NOTE: Make sure to add this include at the top or your page will not be able to recognize the web control -->
<%@ Register src="webcontrols/MyTestControl.ascx" tagname="MyTestControl" tagprefix="uc1" %>
 
<!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>Test</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Panel ID="pnlToAddControlTo" runat="server"></asp:Panel>        
    </div>
    </form>
</body>
</html>

Now in the code behind, add this C# code:

protected void Page_Load(object sender, EventArgs e)
{
    // We can access this control from the built-in "ASP" namespace.  The control's name is 
    // auto-generated by Visual Studio in this namespace.
    ASP.webcontrols_mytestcontrol_ascx myTestWebControl = new ASP.webcontrols_mytestcontrol_ascx();
 
    // Now add this control to the panel's control collection we added to the page.
    pnlToAddControlTo.Controls.Add(myTestWebControl);
}