Custom user control with repeating data

790 views Asked by At

Below is code that I'm aiming for. I need a custom user control that can be data bound to, but also contain other content (so just a raw repeater wont suffice). The end goal is something along the lines of:

<MyControls:Control1 runat="server" id="Control1">
    <headertemplate>
        <tr>
            <td>ID</td>
            <td>Username</td>
        </tr>
    </headertemplate>
    <itemtemplate>
        <tr>
            <td><%#((User)Container.DataItem).ID %></td>
            <td><%#((User)Container.DataItem).Username %></td>
        </tr>
    </itemtemplate>
</MyControls>

And:

var users = GetUsersList();
Control1.DataSource = users;
Control1.DataBind();

And looks like this:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="MyControl1.ascx.cs" Inherits="Controls.MyControl1" %>

<asp:PlaceHolder runat="server" ID="Wrapper">

    <h2>Results</h2>

    <table>
        <%=HeaderTemplate%>
        <%
            if(ItemTemplate.AnyItems()){
                foreach(var item in ItemTemplate){

                }
            }
            else
            {
            %>Nothing here<%
            }
        %>
    </table>
    <MyControls:AnotherControl runat="server" />

</asp:PlaceHolder>

I've found a page on ScottGu's Blog that appears to show what I want:
https://weblogs.asp.net/scottgu/Supporting-Templates-with-ASP.NET-User-Controls

But the linked to tutorial 404's now! All other examples I've found don't seem to be well written and very hard to pick apart.

Any help on how to achieve the above would be much appreciated.

1

There are 1 answers

3
VDWWD On

It looks like you are getting 2 different Controls mixed up. UserControl and Repeater (I think).

To bind data in to a Control inside a UserControl, you need to make that Control accessible from the parent. You can do this by creating a public property inside the UserControl.

public Repeater myRepeater
{
    get
    {
        return Repeater1;
    }
    set
    {
        Repeater1 = value;
    }
}

UserControl ascx with the Repeater Control

<table border="1">
    <asp:Repeater ID="Repeater1" runat="server">
        <HeaderTemplate>
            <tr>
                <td>ID</td>
                <td>Username</td>
            </tr>
        </HeaderTemplate>
        <ItemTemplate>
            <tr>
                <td><%# Eval("ID") %></td>
                <td><%# Eval("Username") %></td>
            </tr>
        </ItemTemplate>
    </asp:Repeater>
</table>
<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Button" />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

Now you have access to Repeater1 in the parent due to the public property.

Control1.myRepeater.DataSource = users;
Control1.myRepeater.DataBind();

And leave the control on the aspx parent empty.

<MyControls:Control1 runat="server" id="Control1"></MyControls>