开发者

How to provide 'data' to User Control inside repeater?

开发者 https://www.devze.com 2023-03-16 06:42 出处:网络
Can somebody explain the easiest way to provide data to a user control inside a repeater? I have the following:

Can somebody explain the easiest way to provide data to a user control inside a repeater?

I have the following:

Default.aspx

<!-- this.GetData() returns IEnumerable<Object> -->
<asp:Repeater runat="server" datasource='<%#this.GetData()%>'>
    <ItemTemplate>
        <my:CustomControl runat="server" datasource='<%#Container.DataItem %>
    </ItemTemplate>
</asp:Repeater>

Codebehind

    protected void Page_Load(object sender, EventArgs e)
    {
        this.DataBind();
    }

CustomControl.ascx

<!-- Object has property Title -->
<h1><%#this.DataSource.Title%></h1>

Codebehind:

[System.ComponentModel.DefaultBindingProperty("DataSource")]
public partial class CustomControl : System.Web.UI.UserControl
{
    public Item DataSource { get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {
        var x = this.DataSource; //null here
    }

    protected void Page_PreRender(object sender, EventArgs e)
    {
        v开发者_JAVA百科ar x = this.DataSource; //still null
    }
}


You could add properties to the user control then set these during the databind.

like this:

<!-- this.GetData() returns IEnumerable<Object> -->
<asp:Repeater runat="server" datasource='<%#this.GetData()%>'>
    <ItemTemplate>
        <my:CustomControl runat="server" title='<%#Container.DataItem.title %>
    </ItemTemplate>
</asp:Repeater>

Codebehind

protected void Page_Load(object sender, EventArgs e)
{
    this.DataBind();
}

CustomControl.ascx

<!-- Object has property Title -->
<h1><%#this.Title%></h1>

Codebehind:

[System.ComponentModel.DefaultBindingProperty("DataSource")]
public partial class CustomControl : System.Web.UI.UserControl
{
    public Item DataSource { get; set; }

    public string title { get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {
        var x = this.DataSource; //null here
    }

    protected void Page_PreRender(object sender, EventArgs e)
    {
        var x = this.DataSource; //still null
     }
}


I found an elegant solution on a different post here: ASP.NET Loading a User Control in a Repeater by Anthony Pegram

Summary:

Using the repeater's ItemDataBound(object sender, RepeaterItemEventArgs e) event to push info into the Web User Control's properties (that you created).

0

精彩评论

暂无评论...
验证码 换一张
取 消