2009-12-21 100 views
0

我有一个使用母版页的页面。母版页上有2个contentplaceholder。该页面上的内容控件与母版页上的占位符相对应。我需要动态地将usercontrosl插入到这些内容区域中。我似乎无法在运行时获得对内容控件的引用,因此我可以将控件插入到它们中。请参见下面的代码:动态加载控件

母版页:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs"  Inherits="Agile.Portal.Site1" %> 

<!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> 
<asp:ContentPlaceHolder ID="head" runat="server"> 
</asp:ContentPlaceHolder> 
</head> 
<body> 
<form id="form1" runat="server"> 
<div> 
    <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server"> 

    </asp:ContentPlaceHolder> 
</div> 
</form> 
</body> 
</html> 

网页:

<%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true"  CodeBehind="WebForm1.aspx.cs" Inherits="Agile.Portal.WebForm1" %> 
<asp:Content ID="head" ContentPlaceHolderID="head" runat="server"> 
</asp:Content> 
<asp:Content ID="ContentPlaceHolder1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server"> 
</asp:Content> 

代码:

protected override void OnInit(EventArgs e) 
    { 
     // YOU SUCK, you're always null!!! 
     System.Web.UI.WebControls.Content cnt = (System.Web.UI.WebControls.Content)this.FindControl("ContentPlaceHolder1"); 
     Agile.Portal.Framework.BaseModule mod = (Agile.Portal.Framework.BaseModule)LoadControl("~/modules/HTMLModule/HtmlModule.ascx"); 
     cnt.Controls.Add(mod); 
     base.OnInit(e); 
    } 

回答

0

尝试使用:

<%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true"  CodeBehind="WebForm1.aspx.cs" Inherits="Agile.Portal.WebForm1" %> 
<asp:Content ID="head" ContentPlaceHolderID="head" runat="server"> 
</asp:Content> 
<asp:Content ID="ContentPlaceHolder1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server"> 
    <asp:PlaceHolder ID="MyPlaceHolder1" runat="server"/> 
</asp:Content> 

和代码:

protected override void OnInit(EventArgs e) { 
    System.Web.UI.WebControls.PlaceHolder cnt = (System.Web.UI.WebControls.PlaceHolder)this.FindControl("MyPlaceHolder1"); 
    Agile.Portal.Framework.BaseModule mod = (Agile.Portal.Framework.BaseModule)LoadControl("~/modules/HTMLModule/HtmlModule.ascx"); 
    cnt.Controls.Add(mod); 
    base.OnInit(e); 
} 
+0

否定的,占位符也会出现null。 – Darthg8r 2009-12-21 16:07:02

+0

事实上,所有你通过检查this.Controls在网页上是一个单一的控制类型MasterPage。 – Darthg8r 2009-12-21 16:10:26

0

我能够想出这个。虽然很丑,但我能找到TcKs提到的PlaceHolder控件的参考。我从Master-> Form-> Placeholder进行导航。见下面的代码。这告诉我,我需要在母版页上递归的FindControl。

 Agile.Portal.Framework.BaseModule mod = (Agile.Portal.Framework.BaseModule)LoadControl("~/modules/HTMLModule/HtmlModule.ascx"); 
     this.Master.Controls[3].Controls[1].Controls.Add(mod); 

有没有更好的办法?

+0

也许放置“base.OnInit(e);”在开始“覆盖无效OnInit(...)”之后,然后调用FindControl。 – TcKs 2009-12-22 10:37:45

+0

不,仍然为空。 – Darthg8r 2009-12-22 16:00:44