Classic scenario: Take user input, get a search-result and display it in pages to the user. I then need to display buttons for First, Next, Previous etc, and I maintain the users current page in viewstate. All is good, works fine.
Then I need to implement clickable page numbers, ie. 1-2-3-4-5-6 etc.
Rendering them is simple. I generate a linkbutton control at runtime, add commandargument with the page number and add a handler to it, so click are to be handled. Then I add it to a placeholder, and it is displayed as expected.
But then… If I did not already have a shaved head, I would be pulling out my hair getting the events to fire as expected every time.
How should I do this, so my events are always wired up and able to fire when the paging-linkbuttons are called?
Below is the important parts of the code, some pseudo to make it (hopefully) easier to understand, what I am doing.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then Search() End If End Sub Sub Search 'Misc databinding stuff, searches and displays results for the page specified in Me.CurrentPage RenderPagingControls() End Sub Sub RenderPagingControls 'loop throug pagenumbers, Build a linkbutton control, add it to a placeholder AddHandler lbn.Click, AddressOf lbnNumber_Click lblPageNumbers.Controls.Add(lbn) ... End Sub Protected Sub lbnNumber_Click(ByVal sender As Object, ByVal e As EventArgs) Dim b As LinkButton = CType(sender, LinkButton) Me.CurrentPage = CInt(b.CommandArgument) Search() End Sub Public Property CurrentPage() As Integer Get Dim o As Object = Me.ViewState('CurrentPage') If o Is Nothing Then Return 1 Else Return CType(o, Integer) End If End Get Set(ByVal value As Integer) Me.ViewState('CurrentPage') = value End Set End Property Protected Sub lbnNumber_Click(ByVal sender As Object, ByVal e As EventArgs) Dim b As LinkButton = CType(sender, LinkButton) Me.CurrentPage = CInt(b.CommandArgument) Search() End Sub
I’m going to recommend against a LinkButton and recommend Hyperlinks / QueryString parameters instead. For several reasons:
You would redefine your CurrentPage method as (hopefully this is correct, I’m better at C# than vb.net):
Then just add hyperlinks for each page.
Alternative: If you want to use the LinkButton, you might want to consider putting a single LinkButton in a repeater. Then the only event you have to worry about is the OnItemCommand event. Then no dynamic controls or events. Something like this:
Bind this control to an array (or list) of consecutive Integers (as many are there are pages). Then in your doPaging function (as I call it), check RepeaterCommandEventArgs.CommandArgument to get the page number.