C# 动态加载控件

C# 动态加载控件,c#,asp.net,C#,Asp.net,我有一个使用母版页的页面。母版页上有2个内容占位符。页面上有与母版页上的占位符相对应的内容控件。我需要动态地将usercontrosl插入这些内容区域。我似乎无法在运行时获取对内容控件的引用,以便将控件插入其中。见下面的代码: 母版页: <%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs" Inherits="Agile.Portal.Site1" %> <!DOCT

我有一个使用母版页的页面。母版页上有2个内容占位符。页面上有与母版页上的占位符相对应的内容控件。我需要动态地将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:PlaceHolder ID="MyPlaceHolder1" runat="server"/>
 </asp:Content>

我能想出这个。虽然很难看,但我能够找到对TcKs提到的占位符控件的引用。我从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);

有更好的主意吗?

没有,占位符也变成了空。事实上,通过检查此项,您可以得到所有结果。网页上的控件是母版页类型的单个控件。可以将“base.OnInit(e);”放在“override void OnInit(…)”开头,然后调用FindControl。
<%@ 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);
}
        Agile.Portal.Framework.BaseModule mod = (Agile.Portal.Framework.BaseModule)LoadControl("~/modules/HTMLModule/HtmlModule.ascx");
        this.Master.Controls[3].Controls[1].Controls.Add(mod);