Friday, February 18, 2011

Implementing Paging in DataList using ASP.Net / C#



In ASP.Net , the controls commonly used for displaying large data are GridView,DataList,Repeater etc.
GridView has built in paging functionalitiy. DataList is another flexible control in which we can display data with Repeat direction either horizontal or vertical , we can specify the repeatcolums as well. But unfortunately DataList control does't have built-in Paging functionality. You need to implement it. A variety of ways are there. Here I am explaining how to do it with C# code.

My Scenario is to Load all categories starting with a letter when clicking on that letter, but it should show say first 10 categories and the next , prev etc...If clicking another letter load categories starting with that letter and then do paging.

Here is my aspx code


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PagingTest.aspx.cs" Inherits="PagingTest" %>

<!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>
<title>Paging in DataList</title>

</head><body>
<form runat="server">
    <h3>Implementing Datalist Paging </h3>
<a name="BookMark"></a>
<asp:DataList ID="DataList1" runat="server" RepeatColumns="4" 
                                        RepeatDirection="Horizontal">
                                        <ItemTemplate>
                                            <table border="0" cellpadding="0" cellspacing="0" width="100%">
                                                <tr>
                                                    <td align="left" valign="top" width="18">
                                                        &nbsp;</td>
                                                    <td align="left" valign="top" width="225">
                                                        <table border="0" cellpadding="0" cellspacing="0" width="100%">
                                                            <tr>
                                                                <td align="left" valign="middle" width="15">
                                                                    <img height="6" src="images/arrow.jpg" width="3" /></td>
                                                                <td align="left" class="style1" valign="middle">
                                                                    <asp:HyperLink ID="LinkButton2" runat="server" CssClass="listlink" 
                                                                        NavigateUrl='<%# "Search.aspx?mode=1&Search=" + Convert.ToString(Eval("classname"))%>' 
                                                                        Text='<%# Convert.ToString(Eval("classname")) %>'></asp:HyperLink>
                                                                </td>
                                                            </tr>
                                                        </table>
                                                    </td>
                                                </tr>
                                            </table>
                                        </ItemTemplate>
                                    </asp:DataList>
<table width="100%">
  <tr>
    <td width=42%" align="left">
      <asp:label ID="lblCounts" Runat="server"  />
    </td>
    <td width=4% valign="bottom">
      <a href="#" id="First" OnServerClick="ShowFirstPage" runat="server">
      <img src="images/firstpage.gif" border="0"></a>
    </td>
    <td width=4% valign="bottom">
      <a href="#" id="Previous" OnServerClick="ShowPreviousPage" runat="server">
      <img src="images/prevpage.gif" border="0"></a>
    </td>
    <td width=4% valign="bottom">
      <a hhref="#" id="Next" OnServerClick="ShowNextPage" runat="server">
      <img src="images/nextpage.gif" border="0"></a>
    </td>
    <td width=4% valign="bottom">
      <a href="#" id="Last" OnServerClick="ShowLastPage" runat="server">
      <img src="images/lastpage.gif" border="0"></a>
    </td>
    <td width="42%" align="center">
        <asp:Button ID="btnLetterA" runat="server"  Text="A" 
            Width="100px" onclick="btnLetterA_Click"  />
        <asp:Button ID="btnLetterB" runat="server"  Text="B" 
            Width="100px" onclick="btnLetterB_Click" />
        <asp:Button ID="btnLetterC" runat="server"  Text="C" 
            Width="100px" onclick="btnLetterC_Click" />
      </td>
  </tr>
</table>
<asp:label ID="LabelRecordCount" Visible="False" Runat="server" />
<asp:label ID="LabelCurrentIndex" Visible="False" Text="0" Runat="server" />
<asp:label ID="LabelPageSize" Visible="False" Text="30" Runat="server" />
</form>
</body>
</html>

Here is my Code behind


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class PagingTest : System.Web.UI.Page
{
    DataTable dtbl;
 
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            PrevFilter = string.Empty;
            Filter = "A";
            BindTheData();
     
        }
    }
    private void BindTheData()
    {
        if (PrevFilter!=Filter)
        {
            PrevFilter = Filter;
            LabelCurrentIndex.Text = "0";
            dtbl = Search.loadCategories(Filter);
            LabelRecordCount.Text = dtbl.Rows.Count.ToString();
        }
        DataSet dataSet=new DataSet();
        dataSet = Search.loadCategories_ByPage(Filter, int.Parse(LabelCurrentIndex.Text), int.Parse(LabelPageSize.Text));
        DataList1.DataSource = dataSet.Tables["categories"].DefaultView;
        DataList1.DataBind();
        ShowCounts();
    }
    public void ShowFirstPage(object sender, EventArgs e)
    {
        LabelCurrentIndex.Text = "0";
        BindTheData();
    }
    public void ShowPreviousPage(object sender, EventArgs e)
    {
        LabelCurrentIndex.Text = (int.Parse(LabelCurrentIndex.Text) - int.Parse(LabelPageSize.Text)).ToString();
        if (int.Parse(LabelCurrentIndex.Text) < 0)
        {
            LabelCurrentIndex.Text = "0";
        }
        BindTheData();
    }
    public void ShowNextPage(object sender, EventArgs e)
    {
        if (int.Parse(LabelCurrentIndex.Text) + int.Parse(LabelPageSize.Text) < int.Parse(LabelRecordCount.Text))
        {
            LabelCurrentIndex.Text = (int.Parse(LabelCurrentIndex.Text) + int.Parse(LabelPageSize.Text)).ToString();
        }
        BindTheData();
    }
    public void ShowLastPage(object sender, EventArgs e)
    {
        int intMod;
        intMod = int.Parse(LabelRecordCount.Text) % int.Parse(LabelPageSize.Text);
        if (intMod > 0)
        {
            LabelCurrentIndex.Text = (int.Parse(LabelRecordCount.Text) - intMod).ToString();
        }
        else
        {
            LabelCurrentIndex.Text = (int.Parse(LabelRecordCount.Text) - int.Parse(LabelPageSize.Text)).ToString();
        }

        BindTheData();
    }
    private void ShowCounts()
    {
        string curPage = "";
        if (int.Parse(LabelRecordCount.Text) % int.Parse(LabelPageSize.Text) > 0)
        {
            curPage = (Math.Truncate(Convert.ToDecimal(LabelRecordCount.Text) / int.Parse(LabelPageSize.Text) + 1)).ToString();
        }
        else
        {
            curPage = (Math.Truncate(Convert.ToDecimal(LabelRecordCount.Text) / int.Parse(LabelPageSize.Text))).ToString();
        }
        lblCounts.Text = "Showing Page:<b>" + (int.Parse(LabelCurrentIndex.Text) / int.Parse(LabelPageSize.Text) + 1).ToString() + "</b> of <b>" + curPage;
   
    }
    string Filter
    {
        get
        {
            object o = ViewState["Filter"];
            return (o != null) ? (string)o : string.Empty;
        }
        set
        {
            ViewState["Filter"] = value;
        }
    }
    string PrevFilter
    {
        get
        {
            object o = ViewState["PrevFilter"];
            return (o != null) ? (string)o : string.Empty;
        }
        set
        {
            ViewState["PrevFilter"] = value;
        }
    }
  
    protected void btnLetterB_Click(object sender, EventArgs e)
    {
        Filter = "B";
        BindTheData();
    }
    protected void btnLetterC_Click(object sender, EventArgs e)
    {
        Filter = "C";
        BindTheData();
    }
    protected void btnLetterA_Click(object sender, EventArgs e)
    {
        Filter = "A";
        BindTheData();
    }
}
I have a class Search which contains a static function , which calling from the code behind to populate data. Here is the function


public static DataSet LoadCategories_ByPage(string letter, int curIndex, int PageSize)
    {
        DataSet dtCategories = new DataSet();
        using (SqlConnection dbConn = new SqlConnection(source))
        {
            string selectCmd = "select distinct category from category_table where category like '" + letter + "%' order by category asc";
            dbConn.Open();
            if (dbConn.State == ConnectionState.Open)
            {
                using (SqlDataAdapter sqlAdptr = new SqlDataAdapter(selectCmd, dbConn))
                {
                    sqlAdptr.Fill(dtCategories, curIndex, PageSize, "categories");
                }

            }
        }

        return dtCategories;
    }

1 comment: