[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 268
  • Last Modified:

Need help with numeric pagelink, its one page behind.

Hi.

Im almost got this to work, but its a page behind.

I got some data 13 Records, 5 records on a page, give 3 pages.

if i start the script i get this page
Pagename.aspx (this page is page 1)
Pagename.aspx?Page=1 (this page is page 2)
Pagename.aspx?Page=2 (this page is page 3)

I need this to know that if Page = Nothing then Page=1
Can someone help me with the right page numeric number !?
So Page 3 is Pagename.aspx?Page=3
Page 2 = Pagename.aspx?Page=2
And Page 1 = Pagename.aspx and Pagename.aspx?Page=1

My code.
Imports System.Data
Imports System.Data.OleDb

Partial Class gridview_EX_Default2
    Inherits System.Web.UI.Page

    Dim pagedData As New PagedDataSource

    Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
        doPaging()
    End Sub

    Public Function getTheData() As DataTable
        'Get data from DB using DataSet 
        Using connection As OleDbConnection = New OleDbConnection(ConfigurationManager.ConnectionStrings("MyConnStr").ConnectionString)
            Dim sql As String = "SELECT * FROM TableTest"
            Using adapter As OleDbDataAdapter = New OleDbDataAdapter(sql, connection)
                Dim ds As New DataSet()
                adapter.Fill(ds, "Portfolio_items")
                Return ds.Tables("Portfolio_items").Copy
            End Using
        End Using
    End Function

    Public Sub doPaging()
        pagedData.DataSource = getTheData().DefaultView
        pagedData.AllowPaging = True
        pagedData.PageSize = 5 'Maximum number of records to show per page

        Try
            pagedData.CurrentPageIndex = Int32.Parse(Request.QueryString("Page")).ToString()
        Catch ex As Exception
            pagedData.CurrentPageIndex = 0
        End Try

        btnPrev.Visible = (Not pagedData.IsFirstPage)
        btnNext.Visible = (Not pagedData.IsLastPage)
        btnFirst.Visible = (Not pagedData.IsFirstPage)
        btnLast.Visible = (Not pagedData.IsLastPage)

        pageNumber.Text = (pagedData.CurrentPageIndex) & " of " & pagedData.PageCount

        'Make the numeric pagelink
        If pagedData.CurrentPageIndex = 1 AndAlso pagedData.DataSourceCount > pagedData.PageSize Then
            pageNumberLink.Text = "Pages: 1"
        ElseIf pagedData.DataSourceCount = 0 Then
            pageNumberLink.Text = "No data to display."
        ElseIf pagedData.CurrentPageIndex > 1 AndAlso pagedData.DataSourceCount > pagedData.PageSize Then
            pageNumberLink.Text = "Pages: <a href='" & Request.CurrentExecutionFilePath & "?Page=1' style='text-decoration:none;' >1</a>"
        End If


        For i As Integer = 2 To pagedData.PageCount
            If i = pagedData.CurrentPageIndex Then
                pageNumberLink.Text = pageNumberLink.Text + " , " & i.ToString()
            Else
                pageNumberLink.Text = pageNumberLink.Text + " , <a href='" & Request.CurrentExecutionFilePath & "?Page=" & i.ToString() & "' style='text-decoration:none;'>" & i.ToString() & "</a>"

            End If
        Next

        'Print the data
        theDataList.DataSource = pagedData
        theDataList.DataBind()
        recordsCount.Text = pagedData.DataSourceCount 'Show Total Records

    End Sub

    Private Sub btnNext_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnNext.Click
        Response.Redirect(Request.CurrentExecutionFilePath & "?Page=" & (pagedData.CurrentPageIndex + 1))
    End Sub

    Private Sub btnPrev_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnPrev.Click
        Response.Redirect(Request.CurrentExecutionFilePath & "?Page=" & (pagedData.CurrentPageIndex - 1))
    End Sub

    Private Sub btnLast_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnLast.Click
        Response.Redirect(Request.CurrentExecutionFilePath & "?Page=" & (pagedData.PageCount - 1))
    End Sub

    Private Sub btnFirst_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnFirst.Click
        Response.Redirect(Request.CurrentExecutionFilePath & "?Page=" & (pagedData.CurrentPageIndex = 0))
    End Sub

End Class

Open in new window

0
tjgrindsted
Asked:
tjgrindsted
  • 11
  • 10
1 Solution
 
Bob LearnedCommented:
What kind of control are you using with the PagedDataSource?  Are you handling binding different on page load and page post-back?
0
 
tjgrindstedAuthor Commented:
hmm i dont know, im new to this, have that something to say !?
0
 
Bob LearnedCommented:
It looks like the PagedDataSource is part of an extended GridView class (gridview_EX_Default2), but I can't see the HTML declaration for the control in the .aspx page or .ascx control...
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
tjgrindstedAuthor Commented:
Ahh

Its bc i started to call the folder gridview_EX, but its a Datalist and its working fine, i just have some problems with the numeric link.
0
 
Bob LearnedCommented:
I see this event handler:

    Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
        doPaging()
    End Sub

Open in new window


How are you handling it different when the page posts-back (i.e. If Not Page.IsPostBack Then)?
0
 
tjgrindstedAuthor Commented:
its a code (without the numeric paginglink) i have found, and then im have tryed to add the numeric paginglink, there was no if not page.is postback, so i dont know that part, is that importent !? if yes how do i fix this error then !? as writing im new to this.
0
 
Bob LearnedCommented:
Here is a simple introduction to ASP.NET post-backs:

IsPostBack in ASP.net
http://www.java-samples.com/showtutorial.php?tutorialid=1083

Important concept:

if (! IsPostBack)
   {
      //  Do the expensive operations only the 
      //  first time the page is loaded.
   }

Open in new window


Persist the data to cache or session variable, and re-bind to a restored version, and don't re-bind with heavy operation again.
0
 
tjgrindstedAuthor Commented:
ok but have the error something to do with the post back !?
0
 
Bob LearnedCommented:
A lot of what happens with ASP.NET is about the page life-cycle, which post-backs are a major part of.  I have no idea what the real problem is, but post-back handling is usually the first place I start to look.

I do see where you are loading the data from the database every time which is a fairly expensive operation, and should only be done on page load.  The PagedDataSource should handle the paging after that.
0
 
tjgrindstedAuthor Commented:
Ok i have looked at another ex. and i cant get the numeric paginglink to the Datalist ID="dlPaging".
I did what u ask me to, about PostBack I dont know if I load the Data from the DB to many times, but hope u can help me.
(again the folder the ex. is in, have the name "gridview_EX")

I get the data, the right Count and the Paging is working, im not getting the Numeric Paging link.

Code.
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default3.aspx.vb" Inherits="gridview_EX_Default3" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form ID="form1" runat="server">
    <div>
    
        <asp:Datalist ID="dListItems" runat="server" RepeatColumns="1" RepeatDirection="Horizontal">
     <ItemTemplate>
      <table border="0" cellpadding="0">
       <tr>
        <td>
         <font color="#49176d" size="2">
          <center><%# Eval("test_info")%></center>
         </font>
       <tr>
        <td>
         <%# Eval("test_cat") %>
        </td>
        </tr><tr>
        <td>
         <%# Eval("test_id")%>
         </tr><tr>
        <td>
         <%# Eval("test_dato", "{0:M-dd-yyyy}")%>
        </td>
        </td>
       </tr>
       </td> </tr>
      </table>
     </ItemTemplate>
    </asp:DataList>
        <asp:DataList ID="dlPaging"  runat="server" RepeatColumns="1" RepeatDirection="Vertical"></asp:DataList>

        <asp:ImageButton ID="lbtnFirst" runat="server" ImageUrl="images/paging_arrow_first.png"></asp:ImageButton>
        <asp:ImageButton ID="lbtnPrevious" runat="server" ImageUrl="images/paging_arrow_prev.png"></asp:ImageButton>
        <asp:ImageButton ID="lbtnNext" runat="server" ImageUrl="images/paging_arrow_next.png"></asp:ImageButton>
        <asp:ImageButton ID="lbtnLast" runat="server" ImageUrl="images/paging_arrow_last.png"></asp:ImageButton>
        <br /><br />
        <asp:Label ID="lblPageInfo" runat="server"></asp:Label>
        <br /><br />
        <asp:Label ID="lblRecordsCount" runat="server"></asp:Label>
    </div>
    </form>
</body>
</html>

Open in new window


Code_Behind
Imports System.Data
Imports System.Data.OleDb

Partial Class gridview_EX_Default3
    Inherits System.Web.UI.Page


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If Not IsPostBack Then
            Me.BindItemsList()
        End If
    End Sub

    'There are three get, set properties, 1-CurrentPage (To keep current page index), 2-fistIndex & 3-lastIndex (These two properties are used to for paging DataList).
    Private Property CurrentPage() As Integer
        Get
            Dim objPage As Object = ViewState("_CurrentPage")
            Dim _CurrentPage As Integer = 0
            If objPage Is Nothing Then
                _CurrentPage = 0
            Else
                _CurrentPage = CInt(objPage)
            End If
            Return _CurrentPage
        End Get
        Set(value As Integer)
            ViewState("_CurrentPage") = value
        End Set
    End Property
    Private Property firstIndex() As Integer
        Get

            Dim _FirstIndex As Integer = 0
            If ViewState("_FirstIndex") Is Nothing Then
                _FirstIndex = 0
            Else
                _FirstIndex = Convert.ToInt32(ViewState("_FirstIndex"))
            End If
            Return _FirstIndex
        End Get
        Set(value As Integer)
            ViewState("_FirstIndex") = value
        End Set
    End Property
    Private Property lastIndex() As Integer
        Get

            Dim _LastIndex As Integer = 0
            If ViewState("_LastIndex") Is Nothing Then
                _LastIndex = 0
            Else
                _LastIndex = Convert.ToInt32(ViewState("_LastIndex"))
            End If
            Return _LastIndex
        End Get
        Set(value As Integer)
            ViewState("_LastIndex") = value
        End Set
    End Property

    'a PagedDataSource object to get and set various properties for custom paging.
    Dim pagedData As New PagedDataSource()

    'GetDataTable() method simply returns a DataTable.
    Private Function GetDataTable() As DataTable
        'Get data from DB using DataSet  
        Using connection As OleDbConnection = New OleDbConnection(ConfigurationManager.ConnectionStrings("MyConnStr").ConnectionString)
            Dim sql As String = "SELECT * FROM TableTest"
            Using adapter As OleDbDataAdapter = New OleDbDataAdapter(sql, connection)
                Dim ds As New DataSet()
                adapter.Fill(ds, "tb_Items")
                Return ds.Tables("tb_Items").Copy
            End Using
        End Using
    End Function

    'Method BindItemsList() gets DataTable by calling GetDataTable() method.
    Private Sub BindItemsList()
        Dim dataTable As DataTable = Me.GetDataTable()
        pagedData.DataSource = dataTable.DefaultView
        pagedData.AllowPaging = True
        pagedData.PageSize = 5 'Items on a site MAX 10.
        pagedData.CurrentPageIndex = CurrentPage
        ViewState("TotalPages") = pagedData.PageCount

        Me.lblPageInfo.Text = "Page " & (CurrentPage + 1) & " of " & pagedData.PageCount
        Me.lblRecordsCount.Text = "Total Records " & pagedData.DataSourceCount 'Show Total Records
        Me.lbtnPrevious.Visible = Not pagedData.IsFirstPage 'can be Visible or Enabled
        Me.lbtnNext.Visible = Not pagedData.IsLastPage 'can be Visible or Enabled
        Me.lbtnFirst.Visible = Not pagedData.IsFirstPage 'can be Visible or Enabled
        Me.lbtnLast.Visible = Not pagedData.IsLastPage 'can be Visible or Enabled

        Me.dListItems.DataSource = pagedData
        Me.dListItems.DataBind()
        Me.doPaging()
    End Sub

    'BindItemsList() calls doPaging() method which actually binds paging DataList.
    Private Sub doPaging()
        Dim dt As New DataTable()
        dt.Columns.Add("PageIndex")
        dt.Columns.Add("PageText")

        firstIndex = CurrentPage - 5

        If CurrentPage > 5 Then
            lastIndex = CurrentPage + 5
        Else
            lastIndex = 10
        End If
        If lastIndex > Convert.ToInt32(ViewState("TotalPages")) Then
            lastIndex = Convert.ToInt32(ViewState("TotalPages"))
            firstIndex = lastIndex - 10
        End If

        If firstIndex < 0 Then
            firstIndex = 0
        End If

        For i As Integer = firstIndex To lastIndex - 1
            Dim dr As DataRow = dt.NewRow()
            dr(0) = i
            dr(1) = i + 1
            dt.Rows.Add(dr)
        Next

        Me.dlPaging.DataSource = dt
        Me.dlPaging.DataBind()
    End Sub

    'dlPaging_ItemCommand set’s CurrentPage Property and again makes a call to BindItemsList().
    Protected Sub dlPaging_ItemCommand(ByVal source As Object, ByVal e As DataListCommandEventArgs)
        If e.CommandName.Equals("Paging") Then
            CurrentPage = Convert.ToInt16(e.CommandArgument.ToString())
            Me.BindItemsList()
        End If
    End Sub

    'dlPaging_ItemDataBound will set Enabled equals to false when binding the LinkButton which is currently clicked from paging list.
    Protected Sub dlPaging_ItemDataBound(ByVal sender As Object, ByVal e As DataListItemEventArgs)
        Dim lnkbtnPage As LinkButton = DirectCast(e.Item.FindControl("lnkbtnPaging"), LinkButton)
        If lnkbtnPage.CommandArgument.ToString() = CurrentPage.ToString() Then
            lnkbtnPage.Enabled = False
            lnkbtnPage.Style.Add("fone-size", "14px")

            lnkbtnPage.Font.Bold = True
        End If
    End Sub

    'Event Handlers for next, previous, first & last LinkButton’s.
    Protected Sub lbtnNext_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles lbtnNext.Click
        CurrentPage += 1
        Me.BindItemsList()
    End Sub
    Protected Sub lbtnPrevious_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles lbtnPrevious.Click
        CurrentPage -= 1
        Me.BindItemsList()
    End Sub
    Protected Sub lbtnLast_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles lbtnLast.Click
        CurrentPage = (Convert.ToInt32(ViewState("TotalPages")) - 1)
        Me.BindItemsList()
    End Sub
    Protected Sub lbtnFirst_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles lbtnFirst.Click
        CurrentPage = 0
        Me.BindItemsList()
    End Sub

End Class

Open in new window

0
 
Bob LearnedCommented:
I am confused about that "paging link" that you are referring to.  Can you please point it out to me?
0
 
tjgrindstedAuthor Commented:
'BindItemsList() calls doPaging() method which actually binds paging DataList.
    Private Sub doPaging()
        Dim dt As New DataTable()
        dt.Columns.Add("PageIndex")
        dt.Columns.Add("PageText")

        firstIndex = CurrentPage - 5

        If CurrentPage > 5 Then
            lastIndex = CurrentPage + 5
        Else
            lastIndex = 10
        End If
        If lastIndex > Convert.ToInt32(ViewState("TotalPages")) Then
            lastIndex = Convert.ToInt32(ViewState("TotalPages"))
            firstIndex = lastIndex - 10
        End If

        If firstIndex < 0 Then
            firstIndex = 0
        End If

        For i As Integer = firstIndex To lastIndex - 1
            Dim dr As DataRow = dt.NewRow()
            dr(0) = i
            dr(1) = i + 1
            dt.Rows.Add(dr)
        Next

        Me.dlPaging.DataSource = dt
        Me.dlPaging.DataBind()
    End Sub

    'dlPaging_ItemCommand set’s CurrentPage Property and again makes a call to BindItemsList().
    Protected Sub dlPaging_ItemCommand(ByVal source As Object, ByVal e As DataListCommandEventArgs)
        If e.CommandName.Equals("Paging") Then
            CurrentPage = Convert.ToInt16(e.CommandArgument.ToString())
            Me.BindItemsList()
        End If
    End Sub

    'dlPaging_ItemDataBound will set Enabled equals to false when binding the LinkButton which is currently clicked from paging list.
    Protected Sub dlPaging_ItemDataBound(ByVal sender As Object, ByVal e As DataListItemEventArgs)
        Dim lnkbtnPage As LinkButton = DirectCast(e.Item.FindControl("lnkbtnPaging"), LinkButton)
        If lnkbtnPage.CommandArgument.ToString() = CurrentPage.ToString() Then
            lnkbtnPage.Enabled = False
            lnkbtnPage.Style.Add("fone-size", "14px")

            lnkbtnPage.Font.Bold = True
        End If
    End Sub

Open in new window

0
 
Bob LearnedCommented:
Nope, that's too much detail...

Are you referring to "lnkbtnPage"?
0
 
tjgrindstedAuthor Commented:
yes from the Protected Sub dlPaging_ItemDataBound i dont get the data from this sub so i get the numeric paginglink
0
 
Bob LearnedCommented:
Did you stop data-binding on page post-back?  You still need to bind to something, just not performing a full data retrieval every time.
0
 
tjgrindstedAuthor Commented:
I dont know, Im new to this and trying to understand this "World" i do what im showing in code, I dont know is im stop data-binding on page or not.

If i add OnItemDataBound="dlPaging_ItemDataBound" to the dlPaging Datalist, then i get a
"NullReferenceException was unhandled by user code" for the codeline
If lnkbtnPage.CommandArgument.ToString() = CurrentPage.ToString() Then
in Protected Sub dlPaging_ItemDataBound.
0
 
tjgrindstedAuthor Commented:
I dont know if im stop data-binding, but after adding this, i got it to work.

Main_Page
...
       <asp:DataList ID="dlPaging" runat="server" RepeatDirection="Horizontal" OnItemCommand="dlPaging_ItemCommand" OnItemDataBound="dlPaging_ItemDataBound">
                                    <ItemTemplate>
                                        <asp:LinkButton ID="lnkbtnPaging" runat="server" CommandArgument='<%# Eval("PageIndex") %>'
                                            CommandName="Paging" Text='<%# Eval("PageText") %>'></asp:LinkButton>&nbsp;
                                    </ItemTemplate>
                                    <SeparatorTemplate>&nbsp;|&nbsp;</SeparatorTemplate>
         </asp:DataList>
....

Open in new window


Code_Behind
...
    'dlPaging_ItemDataBound will set Enabled equals to false when binding the LinkButton which is currently clicked from paging list.
    Protected Sub dlPaging_ItemDataBound(ByVal sender As Object, ByVal e As DataListItemEventArgs)
        If e.Item.ItemType <> ListItemType.Separator Then
            Dim lnkbtnPage As LinkButton = DirectCast(e.Item.FindControl("lnkbtnPaging"), LinkButton)
            If lnkbtnPage.CommandArgument.ToString() = CurrentPage.ToString() Then
                lnkbtnPage.Enabled = False
                lnkbtnPage.Style.Add("fone-size", "14px")
                lnkbtnPage.Font.Bold = True
            End If
        End If
    End Sub
...

Open in new window


Can u say if i Stop the data-binding or not !?
0
 
Bob LearnedCommented:
doPaging has these lines that bind data:

     theDataList.DataSource = pagedData
     theDataList.DataBind()

I would suggest this course of action:

1) Build a PagedDataSource on page load

2) Store the PagedDataSource in a Session variable, that is stored on the server per browser session

3) On page postback, get the PagedDataSource from the session variable, and bind to the DataList.
0
 
tjgrindstedAuthor Commented:
do u have an ex. on this !?
0
 
Bob LearnedCommented:
You could come up with a simple test web site, and create a small proof-of-concept to see what I mean.

Using Session variables to maintain state
http://www.coveryourasp.com/Session.asp

HttpSessionState Class
http://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate.aspx#Y2981

Public Sub Page_Load(ByVal sender As Object, ByVal args As EventArgs)
    If Not IsPostBack Then
      If Session("Address") Is Nothing Then
        EnterUserInfoPanel.Visible = True
        UserInfoPanel.Visible = False
      Else
        EnterUserInfoPanel.Visible = False
        UserInfoPanel.Visible = True

        SetLabels()
      End If
    End If
  End Sub

Open in new window


 Protected Sub EnterInfoButton_OnClick(ByVal sender As Object, ByVal args As EventArgs)
    Session("FirstName") = Server.HtmlEncode(FirstNameTextBox.Text)
    Session("LastName") = Server.HtmlEncode(LastNameTextBox.Text)
    Session("Address") = Server.HtmlEncode(AddressTextBox.Text)
    Session("City") = Server.HtmlEncode(CityTextBox.Text)
    Session("StateOrProvince") = Server.HtmlEncode(StateOrProvinceTextBox.Text)
    Session("ZipCode") = Server.HtmlEncode(ZipCodeTextBox.Text)
    Session("Country") = Server.HtmlEncode(CountryTextBox.Text)

    EnterUserInfoPanel.Visible = False
    UserInfoPanel.Visible = True

    SetLabels()
  End Sub

Open in new window

0
 
tjgrindstedAuthor Commented:
thx for the help.
0

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

  • 11
  • 10
Tackle projects and never again get stuck behind a technical roadblock.
Join Now