ASP.NET - Paging in Datalist - Asked By Shamnad K on 18-Jul-11 08:00 AM

I'm trying to add paging to my datalist
dipa ahuja replied to Shamnad K on 18-Jul-11 08:02 AM
Untitled document
Step 1 Take a pageDatasource at page level
PagedDataSource pds = new PagedDataSource();
 
Step 2 Bind gridview
void bind()
   {
     string con = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
     SqlDataAdapter da = new SqlDataAdapter("select * from emp", con);
     DataTable dt = new DataTable();
     da.Fill(dt);
     DataList1.DataSource = dt;
     DataList1.DataBind();
    pds.DataSource = dt.DefaultView;
     pds.AllowPaging = true;
     pds.PageSize = Convert.ToInt16(ddlPageSize.SelectedValue);
     pds.CurrentPageIndex = CurrentPage;
     lnkbtnNext.Enabled = !pds.IsLastPage;
     lnkbtnPrevious.Enabled = !pds.IsFirstPage;
    DataList1.DataSource = pds;
     DataList1.DataBind();
     doPaging();
   }
Step 3 Add function for paging
public int CurrentPage
   {
     get
     {
       if (this.ViewState["CurrentPage"] == null)
         return 0;
       else
         return Convert.ToInt16(this.ViewState["CurrentPage"].ToString());
     }
     set
     {
       this.ViewState["CurrentPage"] = value;
     }
   }
   private void doPaging()
   {
     
    DataTable dt = new DataTable();
     dt.Columns.Add("PageIndex");
     dt.Columns.Add("PageText");
     for (int i = 0; i < pds.PageCount; i++)
     {
       DataRow dr = dt.NewRow();
       dr[0] = i;
       dr[1] = i + 1;
       dt.Rows.Add(dr);
     }
    dlPaging.DataSource = dt;
     dlPaging.DataBind();
   }
 
Full article http://www.aspdotnetcodes.com/Dynamic_Paging_DataList_Sample.aspx
Jitendra Faye replied to Shamnad K on 18-Jul-11 08:03 AM

There is no inbuilt method for paging in datalist control you have to implement custom paging -

for custom paging you have to use PagedDataSource class object,

follow this code-

public partial class paintings2 : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)
{

if (!IsPostBack)
{

try

{

binddata();

}

catch (Exception ee)
{

Response.Write(ee.ToString());

}

}

}

private void binddata()
{

SqlConnection con = new SqlConnection();
con.ConnectionString = main.getconnection();

con.Open();

string strSql = "select * from paintings";
PagedDataSource objpds = new PagedDataSource();

SqlCommand cmd = new SqlCommand(strSql, con);SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;

DataSet ds = new DataSet();

da.Fill(ds,"paintings");DataView dvPainting = new DataView(ds.Tables["paintings"]);
objpds.DataSource = dvPainting;

objpds.AllowPaging = true;
objpds.PageSize = 3;

objpds.CurrentPageIndex = currentPage;

lblCurrentPage.Text = "Page: " + (currentPage + 1).ToString + " of " + objpds.PageCount.ToString();
ArrayList myTotalPages = new ArrayList();

for (int a = 1; a < objpds.PageCount; a++)
{

myTotalPages.Add(a);

}

ddlPage.DataSource = myTotalPages;

ddlPage.DataBind();

ddlPage.SelectedIndex = currentPage;

cmdPrev.Enabled=!objpds.IsFirstPage;

cmdNext.Enabled = !objpds.IsLastPage;


datalist1.DataSource = objpds;

datalist1.DataBind();

}

protected void ddlSortBy_SelectedIndexChanged(object sender, EventArgs e)
{

binddata();

}


public int currentPage
{

get

{

object o = this.ViewState["_currentPage"];
if (0 == null)

return 0;
else

return (int)o;
}

set

{

this.ViewState["_currentPage"] = value;
}

}

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

currentPage -= 1;

binddata();

}

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

currentPage += 1;

binddata();


}

}

Hope this will help you.

Kalit Sikka replied to Shamnad K on 18-Jul-11 08:04 AM
Private Sub BindDataList()
   Dim page As New PagedDataSource

  page.AllowPaging = True
  page.DataSource = ds ‘Here you will write your Dataset
  page.PageSize = 20
  page.CurrentPageIndex = CurrentPage
  dlVideos.DataSource = page     'dlVideos is my Datalist control ID
  dlVideos.DataKeyField = "ID"
  dlVideos.DataBind()

 'according to last and first page...
  imgBtnNext.Visible = Not page.IsLastPage
  imgBtnPrev.Visible = Not page.IsFirstPage
End Sub

 Public Property CurrentPage() As Integer

        Get
            ' look for current page in ViewState

            Dim o As Object = Me.ViewState("_CurrentPage")

            If o Is Nothing Then

                Return 0
            Else
                ' default to showing the first page

                Return CInt(o)

            End If
        End Get

        Set(ByVal value As Integer)

            Me.ViewState("_CurrentPage") = value
        End Set
    End Property

'Previous Button
Protected Sub imgBtnPrev_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles imgBtnPrev.Click
        CurrentPage -= 1
        BindDataList()
End Sub

'Next Button
Protected Sub imgBtnNext_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles imgBtnNext.Click
        CurrentPage += 1
        BindDataList()
End Sub



Refer: http://www.laiqaarif.com/paging-for-datalist-control-asp-net.
Riley K replied to Shamnad K on 18-Jul-11 08:07 AM
You have to use PagedDataSource class for implementing paging in datalist

here is the code for that

public partial class RepeaterPaging : System.Web.UI.Page
{
    PagedDataSource pds;
    NorthWindDataContext dc = new NorthWindDataContext();
    protected void Page_Load(object sender, EventArgs e)
    {
      if (!IsPostBack)
      {
// this method i am using to fetch only first 5 records to show in repeater
        FetchData(5, 0);
      }
      else
      {
        plcPaging.Controls.Clear();
        CreatePagingControls();
      }

    }
// The fetch data method takes 2 arguments take and skip
    protected void FetchData(int take, int skip)
    {
      var query = from p in dc.Customers.OrderBy(o => o.ContactName).Take(take).Skip(skip)
            select new { City = p.City, Name = p.ContactName, count = dc.Customers.Count() };

      pds = new PagedDataSource();


      pds.AllowCustomPaging = true;
      pds.AllowPaging = true;
      pds.DataSource = query;
      pds.PageSize = 5;
     
      rptCustomer.DataSource = pds;
      rptCustomer.DataBind();


      if (!IsPostBack)
      {
        RowCount = query.First().count;
        CreatePagingControls();
      }
    }

I am creating linkbutton controls for paging
    protected void CreatePagingControls()
    {
      for (int i = 0; i < (RowCount / 5) + 1; i++)
      {
        LinkButton lnk = new LinkButton();
        lnk.ID = "lnk" + (i + 1);
        lnk.Text = i.ToString();
        lnk.Click += new EventHandler(Link_Click);
        plcPaging.Controls.Add(lnk);
        Label lblSpacer = new Label();
        lblSpacer.Text = "&nbsp;";
        plcPaging.Controls.Add(lblSpacer);
      }
    }

//on link click i am showing next 5 records
    public void Link_Click(object sender, EventArgs e)
    {
      LinkButton link = (LinkButton)sender;

      int CurrentPage = int.Parse(link.Text);
      int take = CurrentPage * 5;

      int skip = CurrentPage == 0 ? 1 : take - 5;

      FetchData(take, skip);

    }
      

    
//Maintain the rowcount in viewstate
    public int RowCount
    {
      get
      {
        return (int)ViewState["RowCount"];
      }

      set
      {
        ViewState["RowCount"] = value;
      }
    }

}

Try this and let me know
Reena Jain replied to Shamnad K on 18-Jul-11 08:13 AM
hi,

The control is declared on the page as usual DataList controll. To implement paging we added two Panel controls, one at the top of the list and one at the bottom.

<asp:Panel ID="TopPager_Panel" runat="server" BackColor="AliceBlue"
  BorderWidth="1" BorderStyle="Dashed"></asp:Panel>
 <div>
   <asp:DataList ID="Paging_DataList" runat="server" RepeatDirection="Horizontal"
  RepeatColumns="2" CellPadding="4" GridLines="Both">
  <ItemTemplate>
  <div>
  <span><b>Id:</b></span> <span><%#Eval("Name") %></span>
  </div>
  <div>
    <span><b>Name:</b></span> <span><%#Eval("Name") %></span>
  </div>
  </ItemTemplate>
  </asp:DataList>
 </div>
<asp:Panel ID="BottomPager_Panel" runat="server" BackColor="AliceBlue"
  BorderWidth="1" BorderStyle="Dashed"></asp:Panel>

The pager links were built by adding Hyperlink controls at run time inside the Panel controls based on total pages that needed to be displayed.

private void BindPager()
{
  if (_totalPages <= 1)
  {
  TopPager_Panel.Visible = BottomPager_Panel.Visible = false;
  return;
  }
 
  TopPager_Panel.Visible = BottomPager_Panel.Visible = true;
  for (int i = 0; i < _maxPagesInPager; i++)
  {
  HyperLink topLink = new HyperLink();
  HyperLink bottomLink = new HyperLink();
  LiteralControl topLiteral = new LiteralControl(" ");
  LiteralControl bottomLiteral = new LiteralControl(" ");
  topLink.Text = bottomLink.Text = (i + 1).ToString();
  if (_pageIdx != (i + 1))
  {
  topLink.NavigateUrl = bottomLink.NavigateUrl =
    String.Format("~/Default.aspx?pageidx={0}", i + 1);
  }
 
  TopPager_Panel.Controls.Add(topLink);
  TopPager_Panel.Controls.Add(topLiteral);
  BottomPager_Panel.Controls.Add(bottomLink);
  BottomPager_Panel.Controls.Add(bottomLiteral);
  }
}      

here you can notice from the code snippet above that each pager link passes the page index in query string parameter.

Hope  this will help you
Devil Scorpio replied to Shamnad K on 18-Jul-11 08:30 AM
Hi Shamnad,

For adding paging to ur datalist, Following codes are required
1. Code for Navigation Links.
2. ShowFirst and the DataBind method.

Code for Navigation Links

<table width=100% align="right">
    <tr>
      <td width=76% align=left>
      <asp:label ID="lblStatus"
      Runat="server"
      Font-Name="verdana"
      Font-Size="10pt" />
      </td>

      <td width=6%>
      <a href="datalistpaging.aspx#this"
      ID="hrefFirst"
      onserverclick="ShowFirst"
      runat="server"><<<</a>
      </td>

      <td width=6%>
      <a href="datalistpaging.aspx#this"
      ID="hrefPrevious"
      onserverclick="ShowPrevious"
      runat="server"><<</a>
      </td>

      <td width=6%>
      <a href="datalistpaging.aspx#this"
      ID="hrefNext"
      onserverclick="ShowNext"
      runat="server">></a>
      </td>

      <td width=6%>
      <a href="datalistpaging.aspx#this"
      ID="hrefLast"
      onserverclick="ShowLast"
      runat="server">>></a>
      </td>
    </tr>
</table>

ShowFirst and the DataBind method

Public Sub ShowFirst(ByVal s As Object, ByVal e As EventArgs)
  intCurrIndex.Text = "0"
  DataBind()
End Sub

Private Sub DataBind()
  Dim objConn As New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
  Dim objDA As New SqlDataAdapter("exec sp_das_sales_sel", objConn)
  Dim objDS As New DataSet()

  If Not Page.IsPostBack() Then
    objDA.Fill(objDS)
    intRecordCount.Text = CStr(objDS.Tables(0).Rows.Count)
    objDS = Nothing
    objDS = New DataSet()
  End If

  objDA.Fill (objDS, Cint(intCurrIndex.Text), CInt(intPageSize.Text), "Sales")

  dList.DataSource = objDS.Tables(0).DefaultView
  dList.DataBind()
  objConn.Close()
  PrintStatus()
End Sub

Radhika roy replied to Shamnad K on 18-Jul-11 12:51 PM
For this you have to implement paging in datalist control.

follow this code-

using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using Microsoft.VisualBasic;

namespace DatalistPaging
{
    public class PagingDataList : System.Web.UI.Page
    {
      protected System.Web.UI.WebControls.Label lblCurrentIndex;
      protected System.Web.UI.WebControls.Label lblRecordCount;
      protected System.Web.UI.WebControls.DataList dtlCustomers;
      protected System.Web.UI.WebControls.Label lblPageSize;
      protected System.Web.UI.WebControls.Label lblCounts;
      private void Page_Load(System.Object sender, System.EventArgs e)
      {
        if (!Page.IsPostBack())
        {
          BindTheData();
        }
      }
      private void BindTheData()
      {
        SqlConnection objConn = new 

SqlConnection(ConfigurationSettings.AppSettings("NorthwindConnection"));
        string strSql = "SELECT CompanyName, ContactName, ContactTitle, Country, Phone FROM Customers";
        SqlDataAdapter dataAdapter = new SqlDataAdapter(strSql, objConn);
        DataSet dataSet = new DataSet();
        if (!Page.IsPostBack())
        {
          dataAdapter.Fill(dataSet);
          lblRecordCount.Text = (string)dataSet.Tables(0).Rows.Count;
          dataSet = null;
          dataSet = new DataSet();
        }
        dataAdapter.Fill(dataSet, (int)lblCurrentIndex.Text, (int)lblPageSize.Text, "Customers");
        dtlCustomers.DataSource = dataSet.Tables("Customers").DefaultView;
        dtlCustomers.DataBind();
        objConn.Close();
        ShowCounts();
      }

      public void ShowFirstPage(System.Object s, System.EventArgs e)
      {
        lblCurrentIndex.Text = "0";
        BindTheData();
      }

     public void ShowPreviousPage(System.Object s, System.EventArgs e)
      {
        lblCurrentIndex.Text = (string)(int)lblCurrentIndex.Text - (int)lblPageSize.Text;
        if ((int)lblCurrentIndex.Text < 0)
        {
          lblCurrentIndex.Text = "0";
        }
        BindTheData();
      }

      public void ShowNextPage(System.Object s, System.EventArgs e)
      {
        if ((int)(int)lblCurrentIndex.Text + (int)lblPageSize.Text < (int)lblRecordCount.Text)
        {
          lblCurrentIndex.Text = (string)(int)lblCurrentIndex.Text + (int)lblPageSize.Text;
        }
        BindTheData();
      }

      public void ShowLastPage(System.Object s, System.EventArgs e)
      {
        int intMod = 0;
        intMod = (int)lblRecordCount.Text % (int)lblPageSize.Text;
        if (intMod > 0)
        {
          lblCurrentIndex.Text = (string)(int)lblRecordCount.Text - intMod;
        }
        else
        {
          lblCurrentIndex.Text = (string)(int)lblRecordCount.Text - (int)lblPageSize.Text;
        }
        BindTheData();
      }
      private void ShowCounts()
      {
        lblCounts.Text = "|Total Rows: <b>" + lblRecordCount.Text;
        lblCounts.Text += "</b>  |  Page:<b> ";
        lblCounts.Text += (string)(int)(int)lblCurrentIndex.Text / (int)lblPageSize.Text + 1;
        lblCounts.Text += "</b> of <b>";
        if (((int)lblRecordCount.Text % (int)lblPageSize.Text) > 0)
        {
          lblCounts.Text += (string)Conversion.Fix((int)lblRecordCount.Text / (int)lblPageSize.Text + 1);
        }
        else
        {
          lblCounts.Text += (string)Conversion.Fix(lblRecordCount.Text) / (int)lblPageSize.Text;
        }
        lblCounts.Text += "</b> |";


      }

    }

}


Hope this will help you.