Thursday, February 19, 2009

How to nest web user controls dynamically?

When you use nested Web User Controls and you load them with the LoadControl method, add these controls in PlaceHolder.Controls collection (or other controls except the Page class)


Example code

wucMain.aspx.cs


protected void Page_Load(object sender, EventArgs e)
{
wucSub lMain = (wucSub)Page.LoadControl("Windows/wucSub.ascx");
Controls.Add(lMain);
}

wucMain.aspx
<strong>Main</strong><br /><asp:ListBox runat="server" ID="lstItems" />


wucSub.aspx.cs

no code behind



wucSub.aspx
<strong>Main</strong><br /><asp:ListBox runat="server" ID="lstItems" />


Test.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
wucMain1 lMain = (wucMain1)Page.LoadControl("Windows/wucMain.ascx");
Controls.Add(lMain);
}


Test.aspx
<!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>
</div>
</form>
</body>
</html>

When you build and run these pages, you will get the following error message
"Control 'ctl02_lstItems' of type 'ListBox' must be placed inside a form tag with runat=server."



How can you solve this?

Do not use Page.Controls.Add or Controls.Addd but specify to which Controls collection these these controls must be added and use there a PlaceHolder (panel or other control). So the correct implemention will be


wucMain.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
wucSub lMain = (wucSub)Page.LoadControl("Windows/wucSub.ascx");
plhSub.Controls.Add(lMain);
}


wucMain.aspx
<strong>Main</strong><br /><asp:ListBox runat="server" ID="lstItems" /><asp:PlaceHolder runat="server" ID="plhSub" />


wucSub.aspx.cs

no code behind



wucSub.aspx
<strong>Main</strong><br /><asp:ListBox runat="server" ID="lstItems" />

Test.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
wucMain1 lMain = (wucMain1)Page.LoadControl("Windows/wucMain.ascx");
plhMain.Controls.Add(lMain);
}

Test.aspx
<!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 runat="server" ID="plhMain" />
</div>
</form>
</body>
</html>

No comments:

Post a Comment