I prefer javascript / ajax solution but I think there is nothing wrong with your code.
I did small example. Here is same solution as you have. Advantage is that control is loaded only in case of click.
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLink_Click(object sender, EventArgs e)
{
var uc = (UserControl)Page.LoadControl("~/WebUserControl1.ascx");
pnl.Controls.Add(uc);
}
}
Here is example where user control is loaded in Page_Load event and in case of click (btnLink_Click) user control is added to panel. It works same as your solution but user control can be loaded (processed in memory not redered) even if is not needed.
public partial class Default : System.Web.UI.Page
{
UserControl uc;
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack) // This condition is not needed but we know that click is always postback
uc = (UserControl)Page.LoadControl("~/WebUserControl1.ascx");
}
protected void btnLink_Click(object sender, EventArgs e)
{
pnl.Controls.Add(uc);
}
}
Here is solution which I prefer, it's based on visible property. In case that user control is not visible it's not rendered to output. Sure it's not very practival in case of table with lot of cells as a control container instead of panel.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>
<%@ Register Src="~/WebUserControl1.ascx" TagName="ucrCtrl" TagPrefix="ctr" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnLink" runat="server" Text="Add" OnClick="btnLink_Click" />
<asp:Panel runat="server" ID="pnl">
<ctr:ucrCtrl runat="server" ID="usrCtrl" Visible="false" />
</asp:Panel>
</div>
</form>
</body>
</html>
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLink_Click(object sender, EventArgs e)
{
usrCtrl.Visible = true;
}
}
}