Wednesday, March 28, 2007

Datagrids made easy

People seem to struggle with .NET datagrids. Personally I like them as I think they are pretty powerful, however they don't quite work for me as I want so I have created a web user control that I use instead.

This control has a datagrid on it which is exposed as a property, it also has four buttons for navigation (first, previous, last and next buttons) as I prefer to list the page numbers in the datagrid headings.

The code for these buttons is very simple as follows -
Private Sub butFirst_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles butFirst.Click
Me.dgData.CurrentPageIndex = 0
BindData()
End Sub

Private Sub butPrev_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles butPrev.Click
Me.dgData.CurrentPageIndex = Math.Max(1, Me.dgData.CurrentPageIndex - 1)
BindData()
End Sub

Private Sub butNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles butNext.Click
Me.dgData.CurrentPageIndex = Math.Min(Me.dgData.CurrentPageIndex + 1, Me.dgData.PageCount)
BindData()
End Sub

Private Sub butLast_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles butLast.Click
Me.dgData.CurrentPageIndex = Me.dgData.PageCount
BindData()
End Sub

If you remember that the first page is number 0 then this should all make sense.

I also realised that the data that my grids are to show tends to be that from the main database I babysit. I already have a class which calls this in a couple of lines and returns a dataset. This means that all I need to do to my datagrid control is to give it a StoredProcedureDataSource type property and then I will be able to create an Intranet full of datafrids

No comments: