我有一個表示嵌套層次結構的類(MyClass),所以該類有一個屬性,它是MyClass的集合。 MyClass也有一個標題屬性動態添加用戶控件到中繼器
爲了在網頁上顯示它,我希望創建一個有中繼器的用戶控件。在項目模板中,我將使用文字顯示標題屬性,並在中繼器的ItemCreated事件上創建一個新的usercontrol實例,並將其添加到中繼器中的當前項目中。
我的問題是,當usercontrol中的Page_Load事件觸發時,如果控件是動態添加的,即使我調用EnsureChildControls,repMyClass repeater poroperty也爲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);
}
}
}
}
你可以編輯這個來解釋,也許清理這個。我想也許你在這句話中有一半編輯沒有完成? 「我的問題是,當Page_Load事件首先用於動態添加的控件時,repNyClass repeater poroperty爲null」 – chrismay