动态加载控件

时间:2009-12-21 15:50:56

标签: c# asp.net

我有一个使用母版页的页面。母版页上有2个contentplaceholders。该页面上有内容控件,对应于母版页上的占位符。我需要动态地将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);
    }

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:0)

我能够想出这个。虽然丑陋,但我能找到TcKs提到的PlaceHolder控件的引用。我是通过从Master-&gt; Form-&gt;占位符导航得到的。见下面的代码。这告诉我的是我在母版页上需要一个递归的FindControl。

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

有更好的想法吗?