我有一个类(MyClass),它代表一个嵌套层次结构,因此该类有一个属性,它是 MyClass 的集合。 MyClass 还有一个 title 属性
为了在网页上显示它,我希望创建一个具有中继器的用户控件。在项目模板中,我将使用文字来显示标题属性,并且在转发器的 ItemCreated 事件中,我将创建用户控件的新实例,并将其添加到转发器中的当前项目中。
我的问题是,当用户控件中的 Page_Load 事件触发时,如果该控件是动态添加的,即使我调用 EnsureChildControls,repMyClass 转发器属性也为 null。我在这里错过了什么吗?如果我创建一个中继器并将我的 userctonrol 放入项目模板中,它就可以正常工作。我不能让它动态工作吗?
用户控制:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="MyControl.ascx.cs" Inherits="MyControl" %>
Items:<br/>
<asp:Repeater ID="repMyClass" runat="server" EnableViewState="false"
OnItemCreated="repMenuItems_ItemCreated">
<HeaderTemplate><ul><HeaderTemplate>
<ItemTemplate>
<li><%# Eval("Title") %>
<div><asp:PlaceHolder ID="SubItemPlaceholder" runat="server" /></div>
</li></ItemTemplate>
<FooterTemplate></ul></FooterTemplate>
</asp:Repeater>
用户控制代码:
public partial class MyControl: System.Web.UI.UserControl
{
public IEnumerable<MyClass> ChildItems { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
this.repMyClass.DataSource = ChildItems;
this.repMyClass.DataBind();
}
protected void repMenuItems_ItemCreated(object Sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
{
//Get the MyClass instance for this repeater item
MyClass mcCurrent = (MyClass)e.Item.DataItem;
//If the MyClass instance has child instances
if (mcCurrent.Children != null && mcCurrent.Children.Length > 0)
{
//Add a new user control and set it's property so it can bind
PlaceHolder ph = (PlaceHolder)e.Item.FindControl("SubItemPlaceholder");
MyControl ctl = (MyControl)Page.LoadControl(typeof(MyControl),new object[] {});
ctl.ChildItems = mcCurrent.Children;
ph.Controls.Add(ctl);
}
}
}
}
我很久以前就已经这样做了,使用折叠式创建嵌套报告。
在Index中,当您想要动态添加用户控件实例时:
// Declare Placeholder
PlaceHolder ph = (PlaceHolder)e.Item.FindControl("SubItemPlaceholder")
// Adding some literal controls to header
ph.Controls.Add(new LiteralControl("This is the accordion header!!"));
// Declare new control variable
crt = new Control();
// Load up your User Control
crt = LoadControl("~/MyControl.ascx");
// Check if it has loaded properly
if (crt != null)
{
// GET / SET any custom properties of the User Control
((myClass)crt).title = "Welcome";
// Add the new User Control to the placeholder's controls collection
ph.Controls.Add(crt);
}
Note: 在用户控件中,您必须添加“班级名称”在声明标签中
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="MyControl.ascx.cs" Inherits="myTest" ClassName="myClass" %>
此外,您希望在动态创建实例时公开的任何属性,可以按如下方式声明它们:
public string title { get; set; }
因此,如果您想在为“repMyClass”创建时强制指定一个值,您可以将其设置为属性并以编程方式为其分配您想要的任何值。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)