Thursday, 25 June 2009

In ASP.NET 3.5 a GridView has built in paging, which is nice, and a DataList has a RepeatColumns property so you can display data in columns as well as rows. But, wouldn't it be cool to have a databound control that has both features? Well, you can.

To turn something that looks like this:

1
2
3
4
5
6
7
8
9
Next >

..into something that looks like this:

1 2 3
4 5 6
7 8 9
Next >

..use a GridView and a bit of code behind.

For the purposes of this example you'll need a GridView on your page called 'grdData' with paging enabled and a page size of 9. To create the three column layout two events of the GridView need to be handled.

The first sub handles the RowCreated event and sets up the colspan of the header and pager footer:

--------------------------------------------

Sub grdData_RowItemCreated(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles grdData.RowCreated

If e.Row.RowType = DataControlRowType.Header Or e.Row.RowType = DataControlRowType.Pager Then

'set colspan for header and footer

e.Row.Cells(0).ColumnSpan = 3

End If

End Sub

----------------------

The next sub is the meat of the matter - this handles the DataBound event and moves around cells within the GridView to get the desired layout:

----------------------

Sub grdData_Databound(ByVal sender As Object, ByVal e As System.EventArgs) Handles grdData.DataBound

'give us a nice three column layout rather than default single column

Try

grdData.Rows(0).Cells.Add(grdData.Rows(1).Cells(0))

Catch

End Try

Try

grdData.Rows(0).Cells.Add(grdData.Rows(2).Cells(0))

Catch

End Try

Try

grdData.Rows(3).Cells.Add(grdData.Rows(4).Cells(0))

Catch

End Try

Try

grdData.Rows(3).Cells.Add(grdData.Rows(5).Cells(0))

Catch

End Try

Try

grdData.Rows(6).Cells.Add(grdData.Rows(7).Cells(0))

Catch

End Try

Try

grdData.Rows(6).Cells.Add(grdData.Rows(8).Cells(0))

Catch

End Try

 

End Sub

----------------------

..each step is wrapped in a Try.. Catch as the cells may not be there if less than nine records are returned. To get different layouts just move different cells around.

 



Share this webpage Comments on this webpage