我有一个使用母版页的页面。母版页上有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);
}
否定的,占位符也会出现null。 – Darthg8r 2009-12-21 16:07:02
事实上,所有你通过检查this.Controls在网页上是一个单一的控制类型MasterPage。 – Darthg8r 2009-12-21 16:10:26