[英]Dynamically loaded control
我有一个使用母版页的页面。 母版页上有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);
}
尝试使用:
<%@ 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);
}
我能够想到这个。 虽然很丑,但我能够找到对TcK提到的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);
还有更好的主意吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.