Neste post mostratei com é simples adicionar um User Control dinamicamente em um Webform.
Veja o código da página a seguir:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" %>
<!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:Label ID="lblCabecalho" runat="server" Text="Label"></asp:Label>
<asp:Label ID="lblRodape" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
Para adicionar um User Control entre os labels "lblCabecalho" e "lblRodape" seguiremos os seguintes passos:
1 - Adicione um PlaceHolder entre os labels "lblCabecalho" e "lblRodape". O código ficará da seguinte forma:
...
<asp:Label ID="lblCabecalho" runat="server" Text="Label"></asp:Label>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<asp:Label ID="lblRodape" runat="server" Text="Label"></asp:Label>
...
2 - Use o método LoadControl para passando o nome do UserControl para carregá-lo. E adicione-o ao PlaceHolder.
protected void Page_Load(object sender, EventArgs e)
{
Control ctrl = LoadControl("UserCtrl.ascx");
PlaceHolder1.Controls.Add(ctrl);
}
Espero que tenham gostado!