Michiel van Oosterhout
Michiel van Oosterhout

Reputation: 23084

Is it possible to do custom grouping in the ASP.NET ListView control?

You can only define a GroupItemCount in the ListView, but what if you want to do grouping based on a property of the items in the data source? Sort of an ad-hoc group by. The data source is sorted on this property.

I have seen some examples where some markup in the ItemTemplate was conditionally show, but I want to leverage the GroupTemplate if possible.

Is this possible?

Upvotes: 6

Views: 7374

Answers (2)

blistersonmefingers
blistersonmefingers

Reputation: 21

Yes Nick gave a great lead. Here's my code-behind

Dim sCategory_Descr As String
Function GetGroupHeading(ByVal sGroupName As String) As String
    Dim sReturn As String
    If sCategory_Descr <> sGroupName Then
        sCategory_Descr = sGroupName
        sReturn = "<H5>Category: " & UCase(sGroupName) & "</H5>"
    Else
        sReturn = ""
    End If
        Return sReturn
End Function 

And my item_template

<ItemTemplate>                    
    <tr>
        <td style="background-color:#ccc;" colspan="2" id="tdCategory_Placeholder" runat="server" >
            <asp:Label Font-Bold="true"  ID="Literal1" runat="server" Text='<%# GetGroupHeading(Eval("Category_Descr")) %>' /> 
        </td>
    </tr>                                     
    <tr>
        <td > 
            <asp:DynamicControl1 />                     
        </td>                                               
        <td > 
            <asp:DynamicControl2 />
        </td>                     
    </tr>
</ItemTemplate>

Upvotes: 2

Nick
Nick

Reputation: 5696

When I had to add basic group headings in a repeater I did so with a Literal control in the ItemTemplate:

<asp:Literal runat="server" Text='<%# GetGroupHeading(Eval("Group")) %>' />

The 'GetGroupHeading' method in the code kept track of the previous group heading and sent back '<h2>Group Name</h2>', or an empty string if we were on the same group as the previous item. As I said though, I did this on a Repeater, so not sure if it will cover what you need for a ListView.

Upvotes: 4

Related Questions