DataList Paging

Last post 10-24-2009 1:42 PM by JamesXML. 11 replies.

Sort Posts:

  • DataList Paging

    05-08-2007, 2:38 PM

    Is there a way to set up paging for a datalist?

    Thank you,

    Norbert
    meLearnASP.net
  • Re: DataList Paging

    05-08-2007, 2:53 PM
    • All-Star
      86,678 point All-Star
    • limno
    • Member since 06-10-2005, 7:50 PM
    • Iowa, USA
    • Posts 4,931
    • Moderator
      TrustedFriends-MVPs

    Yes.

    One way you can do this is to use a PagedDataSource. You can find more information from 4guysfromrolla.com site.

    Here is a sample:

    <table width="100%" border="0">

    <tr>

    <td>&nbsp;&nbsp;DataList control with Paging functionality</td>

    </tr>

    <tr>

    <td>&nbsp;&nbsp;<asp:label id="lblCurrentPage" runat="server"></asp:label></td>

    </tr>

    <tr>

    <td>&nbsp;&nbsp;<asp:button id="cmdPrev" runat="server" text=" << " onclick="cmdPrev_Click"></asp:button>

    &nbsp;<asp:button id="cmdNext" runat="server" text=" >> " onclick="cmdNext_Click"></asp:button></td>

    </tr>

    </table>

     

    <asp:DataList ID="DataList1" runat="server" DataKeyField="title_id" >

    <ItemTemplate>

     

    <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# Eval("title_id", "anotherpage.aspx?title_id={0}") %>' Text='<%# Bind("title_id") %>' ></asp:HyperLink>

    title_id:

    <asp:Label ID="title_idLabel" runat="server" Text='<%# Eval("title_id") %>'></asp:Label><br />

    title:

    <asp:Label ID="titleLabel" runat="server" Text='<%# Eval("title") %>'></asp:Label><br />

    type:

    <asp:Label ID="typeLabel" runat="server" Text='<%# Eval("type") %>'></asp:Label><br />

     

    price:

    <asp:Label ID="priceLabel" runat="server" Text='<%# Eval("price","{0:c}") %>'></asp:Label><br />

    <asp:linkbutton ID="Linkbutton3" runat="server" commandname="Edit" text=' <%# "Edit" + Eval("title_id") %>' />

     

    </ItemTemplate>

    </asp:DataList>&nbsp;

    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Pubs %>"

    SelectCommand="SELECT [title_id], [title], [type], [price] FROM [titles]">

    </asp:SqlDataSource>

     

     

     

     

     

    protected void Page_Load(object sender, EventArgs e)

    {

    if (!IsPostBack)

    {

    ItemsGet();

    }

    }

    private void ItemsGet()

    {

    //// Read sample item info from XML document into a DataSet

    //DataSet Items = new DataSet();

    //Items.ReadXml(MapPath("Items.xml"));

    // Populate the repeater control with the Items DataSet

    PagedDataSource objPds = new PagedDataSource();

    //objPds.DataSource = Items.Tables[0].DefaultView;

    DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);

     

    objPds.DataSource = dv;

    objPds.AllowPaging =

    true;

    objPds.PageSize = 3;

    objPds.CurrentPageIndex = CurrentPage;

    lblCurrentPage.Text =

    "Page: " + (CurrentPage + 1).ToString() + " of "

    + objPds.PageCount.ToString();

    // Disable Prev or Next buttons if necessary

    cmdPrev.Enabled = !objPds.IsFirstPage;

    cmdNext.Enabled = !objPds.IsLastPage;

    DataList1.DataSource = objPds;

    DataList1.DataBind();

    }

     

    public int CurrentPage

    {

    get

    {

    // look for current page in ViewState

    object o = this.ViewState["_CurrentPage"];

    if (o == null)

    return 0; // default to showing the first page

    else

    return (int)o;

    }

    set

    {

    this.ViewState["_CurrentPage"] = value;

    }

    }

    protected void cmdPrev_Click(object sender, System.EventArgs e)

    {

    // Set viewstate variable to the previous page

    CurrentPage -= 1;

    // Reload control

    ItemsGet();

    }

    protected void cmdNext_Click(object sender, System.EventArgs e)

    {

    // Set viewstate variable to the next page

    CurrentPage += 1;

    // Reload control

    ItemsGet();

    }

    Limno

    Format your SQL query with instant sql formatter:
    http://www.dpriver.com/pp/sqlformat.htm
  • Re: DataList Paging

    05-08-2007, 3:06 PM
    • Contributor
      3,382 point Contributor
    • KBrocksi_SEC
    • Member since 03-20-2003, 5:39 AM
    • Düsseldorf, Germany
    • Posts 627

    Hi,

    I would recommend reading the following links:

    http://aspalliance.com/articleViewer.aspx?aId=157&pId= (ASP.Net 1.1)

    http://weblogs.asp.net/scottgu/archive/2006/01/07/434787.aspx (ASP.Net 2.0)

    HTH,

    Karsten
  • Re: DataList Paging

    05-08-2007, 3:09 PM
    • All-Star
      37,391 point All-Star
    • Haissam
    • Member since 10-05-2006, 6:25 AM
    • Beirut - Lebanon
    • Posts 5,632

    Check below article

    Extending Datalist Funtionality

    HC

    Haissam Abdul Malak
    MCAD.NET
    | Blog |
  • Re: DataList Paging

    05-08-2007, 10:54 PM
    Answer

    Thank you everyone for assisting me. I was able to get it working.

    Since most of the articles are in C# here is my solution in VB:

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    Dim conn As SqlConnection
    Dim ds As New DataSet

    Dim adapter As SqlDataAdapter

    ' Read the connection string from Web.config
    Dim connectionString As String = _
    ConfigurationManager.ConnectionStrings( _
    "myDB").ConnectionString

    ' Initialize connection
    conn = New SqlConnection(connectionString)

    'use a stored proc
    adapter = New SqlDataAdapter("usp_displayAll", conn)

    adapter.Fill(ds)

    Dim objPds As PagedDataSource = New PagedDataSource
    objPds.DataSource = ds.Tables(0).DefaultView

    objPds.AllowPaging = True
    objPds.PageSize = 5

    Dim CurPage As Integer

    If Not (Request.QueryString("Page") Is Nothing) Then
    CurPage = Convert.ToInt32(Request.QueryString("Page"))
    Else
    CurPage = 1
    End If

    objPds.CurrentPageIndex = CurPage - 1

    lblCurrentPage.Text =

    "Page: " + CurPage.ToString

    If Not objPds.IsFirstPage Then

    lnkPrev.NavigateUrl = Request.CurrentExecutionFilePath +

    "?Page=" + Convert.ToString(CurPage - 1)

    End If

    If Not objPds.IsLastPage Then

    lnkNext.NavigateUrl = Request.CurrentExecutionFilePath +

    "?Page=" + Convert.ToString(CurPage + 1)

    End If

    dlDisplayAll.DataSource = objPds

    dlDisplayAll.DataBind()

    End Sub

    ------------------------------------------------
    Norbert
    meLearnASP.net

    Filed under:
  • Re: DataList Paging

    08-07-2007, 9:00 AM
    • Member
      14 point Member
    • Ahmad Abu Sharkh
    • Member since 05-13-2007, 7:05 AM
    • Jordan,Amman
    • Posts 9

     

     This is code how we can paging datalist in asp.net 2003 Yes

    Imports System.Data
    Imports System.Data.OleDb
    Public Class Paging
        Inherits System.Web.UI.Page

        Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
            'CODEGEN: This method call is required by the Web Form Designer
            'Do not modify it using the code editor.
            InitializeComponent()
        End Sub

    #End Region

      


        Dim pagedData As New PagedDataSource

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


        Dim cs As New DataBase

        Public Function getTheData() As DataTable
            Dim DS As New DataSet
            Dim strConnect As New OleDbConnection(cs.Cs1)
            Dim objSQLAdapter As New OleDbDataAdapter("SELECT * FROM MyPhotos_items", strConnect)
            objSQLAdapter.Fill(DS, "Portfolio_items")

            Return DS.Tables("Portfolio_items").Copy
        End Function

        Public Sub doPaging()
            pagedData.DataSource = getTheData().DefaultView
            pagedData.AllowPaging = True
            pagedData.PageSize = 5

            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)

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

            theDataList.DataSource = pagedData
            theDataList.DataBind()
        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
    =================================================
    <%@ Page Language="vb" AutoEventWireup="false" Codebehind="PagingDS.aspx.vb" Inherits="DC.Paging"%>
    <HTML>
     <HEAD>
      <title>Paging with ASP.NET - DataSet Example - VB.NET</title>
      <META http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
     </HEAD>
     <body>
      <form runat="server" ID="Form1">
       <font size="-1" face="Verdana, Arial, Helvetica, sans-serif">
        <asp:label id="pageNumber" runat="server" /></font>
       <asp:DataList id="theDataList" runat="server" RepeatColumns="3">
        <ItemTemplate>
         <table id="datalist1" border="0" cellpadding="0">
          <tr>
           <td>
            <font color="#49176d" size="2">
             <center><%#DataBinder.Eval(Container.DataItem,"name")%></center>
            </font>
          <tr>
           <td>
            <A href='<%#"img.aspx?item_id="& DataBinder.Eval(Container.DataItem,"item_id")%>'  target=_blank>
             <img height=130 alt="" src='img.aspx?item_id=<%#DataBinder.Eval(Container.DataItem,"item_id")%>' width=130></A>
            <hr>
           </td>
          </tr>
          </td> </tr>
         </table>
        </ItemTemplate>
       </asp:DataList>
       <asp:ImageButton id="btnFirst" runat="server" ImageUrl="images/a-ll-over.gif"></asp:ImageButton>
       <asp:ImageButton id="btnPrev" runat="server" ImageUrl="images/a-l-over.gif"></asp:ImageButton>
       <asp:ImageButton ID="btnNext" Runat="server" ImageUrl="images/a-r-over.gif"></asp:ImageButton>
       <asp:ImageButton id="btnLast" runat="server" ImageUrl="images/a-rr-over.gif"></asp:ImageButton>
      </form>
     </body>
    </HTML>

    Ahmad Abu Sharkh
    Web Developer
    Digital Colors Design Co. LLC
    P.O. Box 17515 Amman 11195
    Mobile: (+962 79) 512 0349
    Email:programmer_ahmad@yahoo.com
    www.digital-colors.com
  • Re: DataList Paging

    06-10-2008, 10:04 PM
    • Member
      44 point Member
    • terbs
    • Member since 11-08-2006, 4:11 AM
    • Posts 47

    Old thread, but have to thank Norbert for that post!

  • Re: DataList Paging

    07-01-2008, 11:45 PM
    • Member
      44 point Member
    • terbs
    • Member since 11-08-2006, 4:11 AM
    • Posts 47

    This code works great, but is there anyway to set the current page to page 1 when you run this code?

    Im using this datalist to display a list of products. If I move to the second page, and filter the list of products still stays on the second page. Even though the list of products after filtered is less than one page.

     

  • Re: DataList Paging

    07-13-2008, 9:29 AM
    • Member
      2 point Member
    • gem_dark
    • Member since 07-13-2008, 1:12 PM
    • Posts 1

     code how we can paging datalist in asp.net 2003 of Ahmad Abu Sharkh show paging in buttom :

    - First Page

    - Last Page

    - Next Page

    - Pre Page.

    Now, How show paging in number href:

    - 1 2 3 4 5 6 7 . . .

    Please help me . . .

  • Re: DataList Paging

    02-05-2009, 5:25 AM
    • Participant
      1,386 point Participant
    • NNM
    • Member since 09-07-2006, 9:04 AM
    • Posts 540

     I use another method, written 100% by a genius (me! lol)

    I love it, because it's simple and requires very little code...

    In your page load:

    - initialize session page counter..

    - call the function that will create the links..

            Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
                If Not IsPostBack Then
                    Session("pageNum") = 1
                  End If
                MakePageLinks()
            End Sub
     

    Here's mine: it counts total records from the datasource; I want 15 items per page here.

            Protected Sub MakePageLinks()
                Dim ds As New DataSet
                Dim db As New DataBase
                ds = db.query("SELECT Count(*) as numObs FROM Observations WHERE reviewed=1")
                Dim numObs As Integer = ds.Tables(0).Rows(0).Item("numObs")
                Dim numPages As Integer = numObs / 15
                For i As Integer = 1 To numPages
                    Dim pageLink As New LinkButton
                    pageLink.Text = "[" + i.ToString + "]"
                    pageLink.CssClass = "normal"
                    pageLink.CommandArgument = i
                    pageLink.PostBackUrl = "#"
                    AddHandler pageLink.Click, AddressOf Me.PageLink_Click
                    pageLinks.controls.add(pageLink)
                    RadAjaxManager1.AjaxSettings.AddAjaxSetting(pageLink, TopObsList, LoadingPanel1)
                Next
            End Sub


     (pageLinks is a tablecell, see below)

    I also use the Telerik controls, so replace      RadAjaxManager1.AjaxSettings.AddAjaxSetting(pageLink, TopObsList, LoadingPanel1)

    with code to register a control as an async trigger to update panel containing the datalist...

            Protected Sub PageLink_Click(ByVal sender As Object, ByVal e As System.EventArgs)
                Session("pageNum") = sender.commandargument
            End Sub

    Below your datalist, add this:

            <br />
            <asp:Table runat="server" ID="alignLinks" Width="700" HorizontalAlign="Center">
            <asp:TableRow>
                <asp:TableCell HorizontalAlign="Left">
                    <asp:LinkButton runat="server" ID="prevPageLink" CssClass="normal" Text="Previous page" PostBackUrl="#"></asp:LinkButton>
                </asp:TableCell>
                <asp:TableCell runat="server" ID="pageLinks">
                </asp:TableCell>
                <asp:TableCell HorizontalAlign="Right">
                    <asp:LinkButton runat="server" ID="nextPageLink" CssClass="normal" Text="Next page" PostBackUrl="#"></asp:LinkButton>
                </asp:TableCell>
            </asp:TableRow>
            </asp:Table>
     

    Here you see I added next and prev links to, here's the code for them:

            Protected Sub nextPageLink_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles nextPageLink.Click
                Session("pageNum") += 1
            End Sub
            Protected Sub prevPageLink_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles prevPageLink.Click
                If Session("pageNum") > 1 Then
                    Session("pageNum") -= 1
                End If
            End Sub

    (they must also be ajaxified)

    And finally, your datasource for the datalist should look something like this:

    <asp:SqlDataSource runat="server" ID="acceptedDS"
        ProviderName="System.Data.SqlClient"
        OldValuesParameterFormatString="original_{0}"
        ConnectionString="<%$ ConnectionStrings:yourConnectionString %>"
        SelectCommand="declare @maxNum integer;SET @maxNum=(SELECT MAX(obs_num) FROM Observations); SELECT DISTINCT TOP 15 * FROM Observations WHERE reviewed=1 AND obs_num<=@maxNum-(15*(@pageNum-1)) ORDER BY obs_num DESC">
        <SelectParameters>
            <asp:SessionParameter Name="pageNum" Type="int32" SessionField="pageNum" />
        </SelectParameters>
    </asp:SqlDataSource> 

    This can easily be adpated to use querystring parameters instead of session.

    Simple, efficient solution... If you know your way around ajax and sql...

    Validation Complete
    ========== Build: 1 succeeded or up-to-date, 0 failed, 0 skipped ==========
    I'll always mark your post(s) as answer when it is!
  • Re: DataList Paging

    10-24-2009, 8:06 AM
    • Member
      2 point Member
    • dm3lions
    • Member since 02-18-2008, 12:51 PM
    • Posts 3

    Norbert, as much as you wouldn't want me to I could kiss you for supplying this solution. Searching for a method

    has written off the last 1 1/2 days of my life!!! Thanks a lot!


  • Re: DataList Paging

    10-24-2009, 1:42 PM
    • Member
      457 point Member
    • JamesXML
    • Member since 04-30-2004, 8:21 AM
    • Orange County CA
    • Posts 92

    Thanks Norbert. Below is my code. I had to make some changes to get your code to work and added a total page count to the lblCurrentPage. Also a heads up that I pass in my stored procedure name because I have a dropdownlist on the page that loads data based on clinics. Just remove sproc variable and put your stored procedure name if you don't need to do that.

     

    Private Sub LoadDL(ByVal sproc As String)
            Dim sConnString As String = ConfigurationManager.ConnectionStrings("VenConn").ToString
            Dim sConn As New SqlConnection(sConnString)
    
            Dim ds As New DataSet
            Dim adapter As SqlDataAdapter
    
            'use a stored proc
            adapter = New SqlDataAdapter(sproc, sConn)
    
            adapter.Fill(ds)
    
            Dim objPds As PagedDataSource = New PagedDataSource
            objPds.DataSource = ds.Tables(0).DefaultView
    
            objPds.AllowPaging = True
            objPds.PageSize = 5
    
    
            Dim CurPage As Integer
    
    
            If Not (ViewState("_CurrentPage") Is Nothing) Then
                CurPage = Convert.ToInt32(ViewState("_CurrentPage").ToString)
            Else
                CurPage = 1
            End If
            objPds.CurrentPageIndex = CurPage - 1
    
            lblCurrentPage.Text = "Page: " + CurPage.ToString + " of " + objPds.PageCount.ToString
    
            'If Not objPds.IsFirstPage Then
            '    lnkPrev.NavigateUrl = Request.CurrentExecutionFilePath + "?Page=" + Convert.ToString(CurPage - 1)
            'End If
    
            'If Not objPds.IsLastPage Then
            '    lnkNext.NavigateUrl = Request.CurrentExecutionFilePath + "?Page=" + Convert.ToString(CurPage + 1)
            'End If
            dlPatientList.DataSource = objPds
    
            dlPatientList.DataBind()
    
        End Sub
    
    Protected Sub cmdPrev_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdPrev.Click
            currentPage -= 1
            FilterList()
        End Sub
    
        Protected Sub cmdNext_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdNext.Click
            currentpage += 1
            FilterList()
        End Sub
    
        Public Property CurrentPage() As Integer
            Get
                Dim o As Object = Me.ViewState("_CurrentPage")
                If o Is Nothing Then
                    Return 0
                Else
                    Return CInt(o.ToString)
                End If
            End Get
            Set(ByVal value As Integer)
                Me.ViewState("_CurrentPage") = value
            End Set
        End Property
    
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            Response.AddHeader("Cache-Control", "no-cache")
            Response.Expires = 0
            Response.AddHeader("Pragma", "no-cache")
    
            If Not IsPostBack Then
                CurrentPage = 1
                LoadDDL()
                FilterList()
    
    
                If Roles.IsUserInRole("physician") Then
                    trPhysiciansReview.Visible = True
                End If
            End If
    
        End Sub
    
    Protected Sub FilterList()
            Dim sProc As String = ""
            ddlClinicFilter.Visible = True
            lblFilter.Visible = True
    
            If Roles.IsUserInRole("admin") Then
                sProc = "spPatientListLoad"
                ddlClinicFilter.Visible = True
                lblFilter.Visible = True
            ElseIf Roles.IsUserInRole("medical director") Then
                sProc = "spPatientListLoad"
                ddlClinicFilter.Visible = True
                lblFilter.Visible = True
            ElseIf Roles.IsUserInRole("ventura") Then
                sProc = "spPatientListLoadVentura"
                ddlClinicFilter.SelectedValue = 2
            ElseIf Roles.IsUserInRole("oxnard") Then
                sProc = "spPatientListLoadOxnard"
                ddlClinicFilter.SelectedValue = 4
            ElseIf Roles.IsUserInRole("conejo") Then
                sProc = "spPatientListLoadConejo"
                ddlClinicFilter.SelectedValue = 6
            ElseIf Roles.IsUserInRole("simi") Then
                sProc = "spPatientListLoadSimi"
                ddlClinicFilter.SelectedValue = 3
            ElseIf Roles.IsUserInRole("santapaula") Then
                sProc = "spPatientListLoadSantaPaula"
                ddlClinicFilter.SelectedValue = 7
            ElseIf Roles.IsUserInRole("epics") Then
                sProc = "spPatientListLoadEPICS"
                ddlClinicFilter.SelectedValue = 8
            Else
                sProc = "spPatientListLoad"
            End If
            LoadDL(sProc)
        End Sub
    
    
    


     

     

     

Page 1 of 1 (12 items)