Saturday, 7 July 2012

Custom Gridview Paging


This is My Designing Page

Here I have taken 4 image buttons to toggle from one page to another page.The four image buttons are First, Previous,Next and Last.The Current Page no and Total Page no. are shown in Labels which will be affected on clicking the Image Buttons. On the Extreme left hand side of the same Div The no.of records are shown with a Label. It is also updated by the click event of Each imagebutton. Another Label is Updated with the No. of Check boxes Selected. It is called by the JavaScript function on each click event of check box in the Grid view.  


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GridCustomPaging.aspx.cs"
    Inherits="MyResearch.GridCustomPaging" %>

<!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>
    <link href="css/common.css" rel="stylesheet" type="text/css" />
    <script type = "text/javascript">
        function checkAll(objRef) {
            var GridView = objRef.parentNode.parentNode.parentNode;
            var inputList = GridView.getElementsByTagName("input");
            for (var i = 0; i < inputList.length; i++) {
                //Get the Cell To find out ColumnIndex
                var row = inputList[i].parentNode.parentNode;
                if (inputList[i].type == "checkbox" && objRef != inputList[i]) {
                    if (objRef.checked) {
                        //If the header checkbox is checked
                        //check all checkboxes
                        //and highlight all rows
                        //row.style.backgroundColor = "aqua";
                        inputList[i].checked = true;
                    }
                    else {
                        //If the header checkbox is checked
                        //uncheck all checkboxes
                        //and change rowcolor back to original
                        if (row.rowIndex % 2 == 0) {
                            //Alternating Row Color
                            //row.style.backgroundColor = "#C2D69B";
                        }
                        else {
                            //row.style.backgroundColor = "white";
                        }
                        inputList[i].checked = false;
                    }
                }
            }
            check();
        }
        function Check_Click(objRef) {
            //Get the Row based on checkbox
            var row = objRef.parentNode.parentNode;
            if (objRef.checked) {
                //If checked change color to Aqua
                //row.style.backgroundColor = "aqua";
            }
            else {
                //If not checked change back to original color
                if (row.rowIndex % 2 == 0) {
                    //Alternating Row Color
                    //row.style.backgroundColor = "#C2D69B";
                }
                else {
                    //row.style.backgroundColor = "white";
                }
            }

            //Get the reference of GridView
            var GridView = row.parentNode;

            //Get all input elements in Gridview
            var inputList = GridView.getElementsByTagName("input");

            for (var i = 0; i < inputList.length; i++) {
                //The First element is the Header Checkbox
                var headerCheckBox = inputList[0];

                //Based on all or none checkboxes
                //are checked check/uncheck Header Checkbox
                var checked = true;
                if (inputList[i].type == "checkbox" && inputList[i] != headerCheckBox) {
                    if (!inputList[i].checked) {
                        checked = false;
                        break;
                    }
                }
            }
            headerCheckBox.checked = checked;

        }
        function check() {

            var grid = document.getElementById("GrdAuthor");  //Retrieve the grid  
            var lbl = document.getElementById("lblSelected");  //Retrieve the grid  
            var inputs = grid.getElementsByTagName("input"); //Retrieve all the input elements from the grid
            var isValid = false;
            var count = 0;
            for (var i = 0; i < inputs.length; i += 1) { //Iterate over every input element retrieved
                if (inputs[i].type === "checkbox") { //If the current element's type is checkbox, then it is wat we need
                    if (inputs[i].checked === true) { //If the current checkbox is true, then atleast one checkbox is ticked, so break the loop
                        count = parseInt(count) + 1;
                    }
                }
            }          
            if (inputs[0].checked === true) {
                count = parseInt(count) - 1
            }
            lbl.innerHTML = count;
        }
</script>

</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <div>
        <h3>
            Custom Gridview Paging and Count Selected Records</h3>
    </div>
    <div>
    </div>
    <div style="width: 902px">
        <table border="0" cellpadding="0" cellspacing="0" style="width: 100%">
            <tr>
                <td colspan="3">
                    <asp:UpdatePanel ID="upnlgrdView" runat="server">
                        <ContentTemplate>
                            <asp:GridView ID="GrdAuthor" runat="server" AutoGenerateColumns="False" PageSize="5"
                                CellPadding="4" ForeColor="#333333" GridLines="None" AllowPaging="True" PageIndex="1">
                                <AlternatingRowStyle BackColor="White" />
                                <Columns>
                                    <asp:TemplateField>
                                        <ItemTemplate>
                                            <asp:CheckBox ID="ChkSelectOne" runat="server" onclick = "Check_Click(this);check();"/>
                                            <asp:HiddenField ID="HdnSerial" runat="server" Value='<% # (GrdAuthor.PageIndex * GrdAuthor.PageSize) +(GrdAuthor.Rows.Count +1)  %>' />
                                        </ItemTemplate>
                                        <HeaderTemplate>
                                          <asp:CheckBox ID="ChkSelectAll" runat="server" onclick = "checkAll(this);" />
                                        </HeaderTemplate>
                                    </asp:TemplateField>
                                    <asp:BoundField DataField="AuthorName" HeaderText="Author Name" />
                                    <asp:BoundField DataField="Comment" HeaderText="Description" />
                                </Columns>
                                <EditRowStyle BackColor="#2461BF" />
                                <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                                <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                                <PagerSettings FirstPageText="" LastPageText="" NextPageText="" PageButtonCount="1"
                                    PreviousPageText="" Visible="False" />
                                <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                                <RowStyle BackColor="#EFF3FB" />
                                <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                                <SortedAscendingCellStyle BackColor="#F5F7FB" />
                                <SortedAscendingHeaderStyle BackColor="#6D95E1" />
                                <SortedDescendingCellStyle BackColor="#E9EBEF" />
                                <SortedDescendingHeaderStyle BackColor="#4870BE" />
                            </asp:GridView>
                        </ContentTemplate>
                    </asp:UpdatePanel>
                </td>
            </tr>
            <tr>
                <td valign="middle" align="left" style="background-color: #D4D0C8; padding-left: 6px;
                    font-size: 9pt; font-style: oblique">
                    <asp:Label ID="lblRecords" runat="server" Text=""></asp:Label>&nbsp;&nbsp;(&nbsp;<asp:Label
            ID="lblSelected" runat="server" Text="0" /> &nbsp;Selected)
                </td>
                <td valign="middle" align="right" style="background-color: #D4D0C8;">
                    <table>
                        <tr>
                            <td>
                                <asp:UpdatePanel ID="upnlGrdPaging" runat="server">
                                    <ContentTemplate>
                                        <table border="0" cellpadding="0" cellspacing="0" style="vertical-align: middle;">
                                            <tr>
                                                <td style="font-size: 8.5pt;">
                                                </td>
                                                <td style="width: 12px">
                                                </td>
                                                <td>
                                                    <asp:ImageButton ID="lnkbtnFirst" runat="server" OnCommand="GetPageIndex" CommandName="First"
                                                        ToolTip="First" ImageUrl="~/Images/PaginFirstInactive.gif" />
                                                </td>
                                                <td style="width: 6px">
                                                </td>
                                                <td>
                                                    <asp:ImageButton ID="lnkbtnPre" runat="server" OnCommand="GetPageIndex" CommandName="Previous"
                                                        ToolTip="Previous" ImageUrl="~/Images/PaginPreInactive.gif" />
                                                </td>
                                                <td style="width: 6px">
                                                </td>
                                                <td style="font-size: 8.5pt;">
                                                    Page
                                                    <asp:Label ID="lblCurrentPage" runat="server"></asp:Label>
                                                    of
                                                    <asp:Label ID="lblTotalPages" runat="server"></asp:Label>
                                                </td>
                                                <td style="width: 6px">
                                                </td>
                                                <td>
                                                    <asp:ImageButton ID="lnkbtnNext" runat="server" OnCommand="GetPageIndex" CommandName="Next"
                                                        ToolTip="Next" ImageUrl="~/Images/PaginNextInactive.gif" />
                                                </td>
                                                <td style="width: 6px">
                                                </td>
                                                <td>
                                                    <asp:ImageButton ID="lnkbtnLast" runat="server" OnCommand="GetPageIndex" CommandName="Last"
                                                        ToolTip="Last" ImageUrl="~/Images/PaginLastInactive.gif" />                                                  
                                                </td>
                                            </tr>
                                        </table>
                                    </ContentTemplate>
                                                                     
                                    <Triggers>
                                        <asp:PostBackTrigger ControlID="lnkbtnPre" />
                                        <asp:PostBackTrigger ControlID="lnkbtnFirst" />
                                        <asp:PostBackTrigger ControlID="lnkbtnNext" />
                                        <asp:PostBackTrigger ControlID="lnkbtnLast" />
                                    </Triggers>
                                                                     
                                </asp:UpdatePanel>
                            </td>
                            <td style="width: 12px">
                            </td>
                            <td>
                                <%--<asp:Button ID="lnkbtnExport" CssClass="Export" ToolTip="Export" runat="server">
                                </asp:Button>--%>
                            </td>
                        </tr>
                    </table>
                </td>
                <td style="width: 6px; background-color: #D4D0C8;">
                </td>
            </tr>
            <tr>
                <td colspan="3">
                    <asp:UpdatePanel ID="upnlMsg" runat="server">
                        <ContentTemplate>
                            <asp:Label ID="lblMessage" runat="server" EnableViewState="false"></asp:Label>
                        </ContentTemplate>
                    </asp:UpdatePanel>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

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;
using System.Data.SqlClient;

namespace MyResearch
{
    public partial class GridCustomPaging : System.Web.UI.Page
    {
        string s;
        protected static int currentPageNumber;
        protected static int PAGE_SIZE;
        int totalRows;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                currentPageNumber = 0;
                PAGE_SIZE = 5;
                FillGrid();
            }
            GrdAuthor.AllowPaging = true;
        }
        private int GetTotalPages(double totalRows)
        {
            int totalPages = (int)Math.Ceiling(totalRows / PAGE_SIZE);

            return totalPages;
        }
        void DisplayPaging()
        {
            if (GrdAuthor.Rows.Count > 0)
            {
                HiddenField hdn = (HiddenField)(GrdAuthor.Rows[0].FindControl("HdnSerial"));
                if (GrdAuthor.PageIndex + 1 == GrdAuthor.PageCount)
                {

                   s = "Result <b>" + hdn.Value + "</b> - <b>" + totalRows + "</b> Of <b>" + totalRows + "</b>";
                }
                else
                {
                    s = "Result <b>" + hdn.Value + "</b> - <b>" + ((GrdAuthor.PageIndex + 1) * GrdAuthor.PageSize).ToString() + "</b> Of <b>" + totalRows + "</b>";
                }
                lblRecords.Text = s;
            }
        }
        protected void GetPageIndex(object sender, CommandEventArgs e)
        {
            lblSelected.Text = "0";
            switch (e.CommandName)
            {
                case "First":
                    currentPageNumber = 0;
                    First();
                    break;

                case "Previous":
                    currentPageNumber = Int32.Parse(lblCurrentPage.Text) - 1;
                    Previous();
                    break;

                case "Next":
                    currentPageNumber = Int32.Parse(lblCurrentPage.Text) + 1;
                    Next();
                    break;

                case "Last":
                    currentPageNumber = Int32.Parse(lblTotalPages.Text) - 1;
                    Last();
                    break;
            }

            FillGrid();
        }
        private void FillGrid()
        {
            try
            {
                SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString);
                SqlDataAdapter da = new SqlDataAdapter("Select AuthorName,Comment from Author", con);
                DataSet ds = new DataSet();
                da.Fill(ds);
                totalRows = ds.Tables[0].Rows.Count;
                lblTotalPages.Text = GetTotalPages(totalRows).ToString();
                if (!IsPostBack)
                {
                    if (totalRows > 0)
                    {
                        GrdAuthor.PageIndex = 0;
                        lblCurrentPage.Text = "1";
                        CheckNext();
                        lnkbtnFirst.Enabled = false;
                        lnkbtnPre.Enabled = false;
                    }
                    else
                    {
                        lblCurrentPage.Text = "0";
                    }
                }
                GrdAuthor.DataSource = ds;
                GrdAuthor.DataBind();
            }
            catch (Exception ex)
            {
                //lblMessage.Text = ex.Message;
            }
            finally
            {

            }
            DisplayPaging();
        }
        void First()
        {
            CheckNext();
            lnkbtnPre.Enabled = false;
            lnkbtnPre.CssClass = "GridPagePreviousInactive";
            lnkbtnPre.ImageUrl = "~/Images/PaginPreInactive.gif";
            lnkbtnFirst.Enabled = false;
            lnkbtnFirst.CssClass = "GridPageFirstInactive";
            lnkbtnFirst.ImageUrl = "~/Images/PaginFirstInactive.gif";
            lblCurrentPage.Text = (currentPageNumber + 1).ToString();
            GrdAuthor.PageIndex = currentPageNumber;
        }
        void Previous()
        {
            CheckNext();
            if (currentPageNumber == 1)
            {
                lnkbtnPre.Enabled = false;
                lnkbtnPre.CssClass = "GridPagePreviousInactive";
                lnkbtnPre.ImageUrl = "~/Images/PaginPreInactive.gif";
                lnkbtnFirst.Enabled = false;
                lnkbtnFirst.CssClass = "GridPageFirstInactive";
                lnkbtnFirst.ImageUrl = "~/Images/PaginFirstInactive.gif";
            }
            else
            {
                lnkbtnPre.Enabled = true;
                lnkbtnPre.CssClass = "GridPagePreviousActive";
                lnkbtnPre.ImageUrl = "~/Images/PaginPre.gif";
                lnkbtnFirst.Enabled = true;
                lnkbtnFirst.CssClass = "GridPageFirstActive";
                lnkbtnFirst.ImageUrl = "~/Images/PaginFirst.gif";
            }
            lblCurrentPage.Text = (currentPageNumber).ToString();
            GrdAuthor.PageIndex = currentPageNumber - 1;
        }
        void CheckNext()
        {
            if (Int32.Parse(lblTotalPages.Text) > 1)
            {
                lnkbtnNext.Enabled = true;
                lnkbtnNext.CssClass = "GridPageNextActive";
                lnkbtnNext.ImageUrl = "~/Images/PaginNext.gif";
                lnkbtnLast.Enabled = true;
                lnkbtnLast.CssClass = "GridPageLastActive";
                lnkbtnLast.ImageUrl = "~/Images/PaginLast.gif";
            }
            else
            {
                lnkbtnNext.Enabled = false;
                lnkbtnNext.CssClass = "GridPageNextInactive";
                lnkbtnNext.ImageUrl = "~/Images/PaginNextInactive.gif";
                lnkbtnLast.Enabled = false;
                lnkbtnLast.CssClass = "GridPageLastInactive";
                lnkbtnLast.ImageUrl = "~/Images/PaginLastInactive.gif";
            }
        }
        void Next()
        {
            if ((currentPageNumber - 1) == (Int32.Parse(lblTotalPages.Text) - 1))
            {
                lnkbtnNext.Enabled = false;
                lnkbtnNext.CssClass = "GridPageNextInactive";
                lnkbtnNext.ImageUrl = "~/Images/PaginNextInactive.gif";
                lnkbtnLast.Enabled = false;
                lnkbtnLast.CssClass = "GridPageLastInactive";
                lnkbtnLast.ImageUrl = "~/Images/PaginLastInactive.gif";
            }
            else
            {
                lnkbtnNext.Enabled = true;
                lnkbtnNext.CssClass = "GridPageNextActive";
                lnkbtnNext.ImageUrl = "~/Images/PaginNext.gif";
                lnkbtnLast.Enabled = true;
                lnkbtnLast.CssClass = "GridPageLastActive";
                lnkbtnLast.ImageUrl = "~/Images/PaginLast.gif";
            }
            lnkbtnPre.Enabled = true;
            lnkbtnPre.CssClass = "GridPagePreviousActive";
            lnkbtnPre.ImageUrl = "~/Images/PaginPre.gif";
            lnkbtnFirst.Enabled = true;
            lnkbtnFirst.CssClass = "GridPageFirstActive";
            lnkbtnFirst.ImageUrl = "~/Images/PaginFirst.gif";
            lblCurrentPage.Text = (currentPageNumber).ToString();
            GrdAuthor.PageIndex = currentPageNumber - 1;
        }
        void Last()
        {
            lnkbtnPre.Enabled = true;
            lnkbtnPre.CssClass = "GridPagePreviousActive";
            lnkbtnPre.ImageUrl = "~/Images/PaginPre.gif";
            lnkbtnFirst.Enabled = true;
            lnkbtnFirst.CssClass = "GridPageFirstActive";
            lnkbtnFirst.ImageUrl = "~/Images/PaginFirst.gif";
            lnkbtnNext.Enabled = false;
            lnkbtnNext.CssClass = "GridPageNextInactive";
            lnkbtnNext.ImageUrl = "~/Images/PaginNextInactive.gif";
            lnkbtnLast.Enabled = false;
            lnkbtnLast.CssClass = "GridPageLastInactive";
            lnkbtnLast.ImageUrl = "~/Images/PaginLastInactive.gif";
            lblCurrentPage.Text = (currentPageNumber + 1).ToString();
            GrdAuthor.PageIndex = currentPageNumber;
        }
    }
}