Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
    {
        var x = this.DataSource; //still null
    }
}
like image 745
Ropstah Avatar asked Jun 30 '11 15:06

Ropstah


1 Answers

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
     }
}
like image 180
Simon Halsey Avatar answered Sep 28 '22 13:09

Simon Halsey