Search code examples
c#asp.netasprepeater

asp:repeater show count of items in each category


I have a simple repeater that gets the 'groups' of 'widgets' The home page lists all of the groups:

<ItemTemplate>
    <tr>
        <td width="60" class="center"><%# DataBinder.Eval(Container.DataItem, "Number") %></td>
        <td><a href="Stories.aspx?ProjectID=<%# DataBinder.Eval(Container.DataItem, "ProjectId") %>"><%# DataBinder.Eval(Container.DataItem, "Name") %></a></td>
        <td><%# DataBinder.Eval(Container.DataItem, "Description") %></td>
    </tr>
</ItemTemplate>

Code Behind

private void LoadForm()
{
    using (MarketingWebContentEntities context = new MarketingWebContentEntities())
    {
        rptGroup.DataSource = (from groups in context.URLGroup
                               select groups).ToList();
        rptGroup.DataBind();
    }
}

I would like within the repeater to show number of 'widgets' within each 'group'. I know I'd need to run a query on the 'widgets' table to see how many items are in that list. I'm just unsure how to add that within the repeater mark-up.


Solution

  • As mentioned in the comment, you could use the ItemDataBound event for this.

    This example is in VB - been a while since I wrote C#, though will give you an idea. I haven't checked it for syntax either, it's more an example to get you up and running.

    In your <ItemTemplate> add yourself, say, a ASP:Label. In this case, it's called myLabel

    So in your code behind, create a private method that will handle the ItemDataBound event.

    Protected Sub myRepeater_ItemDataBound(sender As Object, e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles myRepeater.ItemDataBound
    
        If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then
    
            Dim uG As URLGroup = CType(e.Item.DataItem, URLGroup)
            '' you now have the group for that one item
            '' you should now be able to get additional information needed.
            '' you can also get the myLabel from this item 
            dim lbl as Label = CType(e.Item.FindControl("myLabel", Label)
            '' and set its text to whatever you need
            lbl.Text = MyCounter
    
        End If
    
    End Sub
    

    Hopefully this will get you on your way.

    Here is a link to the MSDN documentation for it too.