ASP.NET Grouping in ListView


Example

asp:ListView introduced in ASP.NET WebForms framework 3.5 is the most flexible of all DataPresentation Controls in the framework. An example of Grouping using ListView (which will come handy as an image gallery)

Objective: To display three images in a row using asp:ListView

Markup

<asp:ListView ID="SportsImageList" runat="server"
    GroupItemCount="3">
    <LayoutTemplate>
        <span class="images-list">
            <ul id="groupPlaceholder" runat="server"></ul>
        </span>
    </LayoutTemplate>
    <GroupTemplate>
        <ul>
            <li id="itemPlaceholder" runat="server"></li>
        </ul>
    </GroupTemplate>
    <ItemTemplate>
        <li>
            <img src='<%# Container.DataItem %>' />
        </li>
    </ItemTemplate>
</asp:ListView>

Code Behind

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
    {
        SportsImageList.DataSource = GetImages();
        SportsImageList.DataBind();
    }
}

private static IEnumerable<string> GetImages()
{
    var images = Enumerable.Range(1, 9) //get numbers 1 to 9
        .Select(i =>
            string.Format("http://lorempixel.com/100/100/sports/{0}/", i)
        ); //convert the numbers to string
    return images;
}

CSS

.images-list ul{
    clear: both;
    list-style-type: none;
}
.images-list ul li{
    float: left;
    padding: 5px;
}

Rendered Output

Sports Images Gallery