Monday, 18 June 2012


How to create custom paging in Data List control?


 

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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>DataList Example</title>
    <style type="text/css">
    .htext
    {
        background-color: #033280;
        color: White;
        font-size: 12px;
        font-weight: bold;   
    }
    .celltext
    {
        background-color: #E9F3F8;
        color: #000000;
        font-size: 12px;
        font-weight: bold;   
    }
    a 
    {
        text-decoration: none;
        font-weight:bold;
    }
    a:hover 
    {
        text-decoration: underline;
    }
  </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table width="700" align="center" cellspacing="0" cellpadding="0">
    <tr>
        <td height="40" colspan="2"><b>DataList Custom Paging Example</b></td>
    </tr>        
    <tr>
    <td width="50%" height="50">
        Select number of items to be displayed per page
    </td>
    <td width="50%">
        <asp:DropDownList ID="ddlIndex" runat="server" AutoPostBack="True" 
            onselectedindexchanged="ddlIndex_SelectedIndexChanged">
        </asp:DropDownList>
    </td>
    </tr>    
     <tr>
        <td align="center" width="100%" colspan="2" valign="top" style="padding-top: 10px;
 padding-bottom: 10px;">
            <asp:DataList runat="server" ID="DListEmp" cellpadding="0" cellspacing="0">                
                <HeaderTemplate>
                <table width="500" bgcolor="#ffffff" cellpadding="0" cellspacing="0">
                <tr>
                <td width="150" align="center" height="30" class="htext"><b>Employee No.</b></td>
                <td width="150" align="center" height="30" class="htext"><b>Employee Name</b></td>
                <td width="150" align="center" height="30" class="htext"><b>Employee Department</b>
</td>
                </tr>
                </HeaderTemplate>                
                <ItemTemplate>
                <tr>
                <td width="150" align="center" height="30" class="celltext"><%#Eval("eno") %></td>
                <td width="150" align="center" height="30" class="celltext"><%#Eval("empname") %></td>
                <td width="150" align="center" height="30" class="celltext"><%#Eval("dept") %></td>
                </tr>                   
                </ItemTemplate>                                  
                <FooterTemplate>
                    </table>
                </FooterTemplate>                
            </asp:DataList>
        </td>
    </tr>         
    <tr>
    <td align="center" height="40" valign="middle" colspan="2">
    <table>
    <tr>
    <td colspan="5">  </td>
    </tr>
    <tr>
    <td width="80" valign="top" align="center"><asp:LinkButton ID="lnkFirst" 
            runat="server" onclick="lnkFirst_Click">First</asp:LinkButton></td>
    <td width="80" valign="top" align="center"><asp:LinkButton ID="lnkPrevious" 
            runat="server" onclick="lnkPrevious_Click">Previous</asp:LinkButton></td>
    <td>
            <asp:DataList ID="DataListPaging" runat="server" RepeatDirection="Horizontal" 
                onitemcommand="DataListPaging_ItemCommand" 
                onitemdatabound="DataListPaging_ItemDataBound">
            <ItemTemplate>
                <asp:LinkButton ID="Pagingbtn" runat="server" CommandArgument='<%# Eval("PageIndex") %>'

 CommandName="newpage" Text='<%# Eval("PageText") %> '></asp:LinkButton> 
            </ItemTemplate>
            </asp:DataList> 
    </td>
    <td width="80" valign="top" align="center">
            <asp:LinkButton ID="lnkNext" runat="server" onclick="lnkNext_Click">Next</asp:LinkButton>
    </td>
    <td width="80" valign="top" align="center">
        <asp:LinkButton ID="lnkLast" runat="server" onclick="lnkLast_Click">Last</asp:LinkButton>
    </td>
    </tr> 
    </table>        
        </td>
    </tr>
    <tr>
    <td align="center" height="40" colspan="2"><asp:Label ID="lblpage" runat="server" Text="">
</asp:Label></td>
    </tr>    
    </table>
    </div>
    </form>
</body>
</html>
---------------
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 _Default : System.Web.UI.Page 
{
    PagedDataSource pgsource = new PagedDataSource();
    int findex, lindex;
    DataRow dr;
    
    protected void Page_Load(object sender, EventArgs e)
    {
        //During first time page load this method call
        if (!Page.IsPostBack)
        {
            BindDataList();
            LoadDDL();
        }
    }

    DataTable GetData()
    {
        DataTable dtable = new DataTable();
        //Create column names for Datatable "dtable" 
        dtable.Columns.Add("eno");
        dtable.Columns.Add("empname");
        dtable.Columns.Add("dept");
        for (int i = 1; i <= 100; i++)
        {
            //Create rows for DataTable "dtable" and assign values for each column
            dr = dtable.NewRow();
            dr["eno"] = i;
            dr["empname"] = "Empname " + i;
            dr["dept"] = "Dept. Name ";
            dtable.Rows.Add(dr);
        }
        //Return DataTable "dtable" with its data
        return dtable;
    }

    private void BindDataList()
    {
        //Create new DataTable dt
        DataTable dt = GetData();
        pgsource.DataSource = dt.DefaultView;

        //Set PageDataSource paging 
        pgsource.AllowPaging = true;
       
        //Set number of items to be displayed in the DataList using drop down list
        if (ddlIndex.SelectedIndex == -1 || ddlIndex.SelectedIndex == 0)
        {
            pgsource.PageSize = 10;
        }
        else
        {
            pgsource.PageSize = Convert.ToInt32(ddlIndex.SelectedItem.Value);
        }
        

        //Get Current Page Index
        pgsource.CurrentPageIndex = CurrentPage;

        //Store it Total pages value in View state
        ViewState["totpage"] = pgsource.PageCount;

        //Below line is used to show page number based on selection like "Page 1 of 20"
        lblpage.Text = "Page " + (CurrentPage + 1) + " of " + pgsource.PageCount;
        
        //Enabled true Link button previous when current page is not equal first page 
        //Enabled false Link button previous when current page is first page
        lnkPrevious.Enabled = !pgsource.IsFirstPage;

        //Enabled true Link button Next when current page is not equal last page 
        //Enabled false Link button Next when current page is last page
        lnkNext.Enabled = !pgsource.IsLastPage;

        //Enabled true Link button First when current page is not equal first page 
        //Enabled false Link button First when current page is first page
        lnkFirst.Enabled = !pgsource.IsFirstPage;

        //Enabled true Link button Last when current page is not equal last page 
        //Enabled false Link button Last when current page is last page
        lnkLast.Enabled = !pgsource.IsLastPage;

        //Bind resulted PageSource into the DataList
        DListEmp.DataSource = pgsource;
        DListEmp.DataBind();

        //Create Paging in the second DataList "DataListPaging"
        doPaging();
    }

    private void doPaging()
    {
        DataTable dt = new DataTable();
        //Add two column into the DataTable "dt" 
        //First Column store page index default it start from "0"
        //Second Column store page index default it start from "1"
        dt.Columns.Add("PageIndex");
        dt.Columns.Add("PageText");

        //Assign First Index starts from which number in paging data list
        findex = CurrentPage - 5;

        //Set Last index value if current page less than 5 then last index added "5"
 values to the Current page else it set "10" for last page number
        if (CurrentPage > 5)
        {
            lindex = CurrentPage + 5;
        }
        else
        {
            lindex = 10;
        }

        //Check last page is greater than total page then reduced it to total no. of page is 
last index
        if (lindex > Convert.ToInt32(ViewState["totpage"]))
        {
            lindex = Convert.ToInt32(ViewState["totpage"]);
            findex = lindex - 10;
        }

        if (findex < 0)
        {
            findex = 0;
        }
        
        //Now creating page number based on above first and last page index
        for (int i = findex; i < lindex; i++)
        {
            DataRow dr = dt.NewRow();
            dr[0] = i;
            dr[1] = i + 1;
            dt.Rows.Add(dr);
        }
        
        //Finally bind it page numbers in to the Paging DataList
        DataListPaging.DataSource = dt;
        DataListPaging.DataBind();
    }

    private int CurrentPage
    {       
        get
        {   //Check view state is null if null then return current index value as "0" else
 return specific page viewstate value
            if (ViewState["CurrentPage"] == null)
            {
                return 0;
            }           
            else
            {
                return ((int)ViewState["CurrentPage"]);
            }            
        }
        set
        {
            //Set View statevalue when page is changed through Paging DataList
            ViewState["CurrentPage"] = value;
        }
    }

    protected void DataListPaging_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName.Equals("newpage"))
        {
            //Assign CurrentPage number when user click on the page number in the Paging
 DataList
            CurrentPage = Convert.ToInt32(e.CommandArgument.ToString());
            //Refresh DataList "DlistEmp" Data once user change page
            BindDataList();
        }
    }

    protected void lnkFirst_Click(object sender, EventArgs e)
    {
        //If user click First Link button assign current index as Zero "0" then refresh DataList "DlistEmp" Data.
        CurrentPage = 0;
        BindDataList();
    }

    protected void lnkLast_Click(object sender, EventArgs e)
    {
        //If user click Last Link button assign current index as totalpage then refresh DataList "DlistEmp" Data.
        CurrentPage = (Convert.ToInt32(ViewState["totpage"]) - 1);
        BindDataList();
    }

    protected void lnkPrevious_Click(object sender, EventArgs e)
    {
        //If user click Previous Link button assign current index as -1 it reduce existing page index.
        CurrentPage -= 1;
        //refresh DataList "DlistEmp" Data
        BindDataList();
    }

    protected void lnkNext_Click(object sender, EventArgs e)
    {
        //If user click Next Link button assign current index as +1 it add one value to existing page index.
        CurrentPage += 1;

        //refresh DataList "DlistEmp" Data
        BindDataList();
    }

    void LoadDDL()
    {
        //Below code is used to bind values in the drop down list
        for (int i = 1; i <= 10; i++)
        {
            ddlIndex.Items.Add(i.ToString());
        }
        ddlIndex.Items.Insert(0, new ListItem("--Select--", "--Select--"));    
    } 
  
    protected void ddlIndex_SelectedIndexChanged(object sender, EventArgs e)
    {
        //Set Default current index Zero default and refresh it page size based on Drop Down
 List selected
        CurrentPage = 0;
        BindDataList();
    }
    protected void DataListPaging_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        //Enabled False for current selected Page index
        LinkButton lnkPage = (LinkButton)e.Item.FindControl("Pagingbtn");
        if (lnkPage.CommandArgument.ToString() == CurrentPage.ToString())
        {
            lnkPage.Enabled = false;            
        }
    }
}

No comments:

Post a Comment