When you want to add a pager to a grid inside a WebPart to implement paging, you will notice that some event handlers can be left blank. Suppose you create a new SPGridView in the CreateChildControls, set paging to true and PageSize to something less than the amount of records you are going to add and you add that grid to the WebPart controls. Next you add a toolbar to the WebPart controls and create a new SPGridViewPager. Assign the Id of the grid to the GridViewId of the pager, add some handlers for the ClickNext and ClickPrevious event and add the control to the ToolBar controls. You can just implement the Click functions and leave them empty. In the OnPreRender you add the datasource to the grid and bind the grid. Easy to implement, nothing to worry about.
Code example:
Protected Overrides Sub CreateChildControls()
grid = New SPGridView()
grid.ID = Me.ID + “Grid”
grid.AllowPaging = true
grid.PageSize = 10
pager = New SPGridViewPager()
pager.ID = Me.ID + “Pager”
pager.GridViewId = grid.ID
AddHandler pager.ClickNext, AddressOf pager_ClickNext
AddHandler pager.ClickPrevious, AddressOf pager_ClickPrevious
gridToolBar = Page.LoadControl(“~/_controltemplates/ToolBar.ascx”)
gridToolBar.RightButtons.Controls.Add(pager)
Me.Controls.Add(grid)
Me.Controls.Add(gridToolBar)
End Sub
Protected Overrides Sub OnPreRender(ByVal e as EventArgs)
MyBase.OnPreRender(e)
‘No further details about the method below.
’It adds a datasource to the grid with more
’than 10 records.
grid_AddDataSource()
grid.DataBind()
End Sub
Private Sub pager_ClickNext(ByVal sender As Object, ByVal e As EventArgs)
‘Intentionally left blank, grid is binded in OnPreRender
End Sub
Private Sub pager_ClickPrevious(ByVal sender As Object, ByVal e As EventArgs)
‘Intentionally left blank, grid is binded in OnPreRender
End Sub
You will see that first the CreateChildControls is called, next a click handler and as last the OnPreRender. During the click handler, the current pageindex is updated automatically.