CodeSnip: Customized DataGrid Paging
page 1 of 1
Published: 09 May 2006
Unedited - Community Contributed
Abstract
In this article, Surya demonstrates how to create a customized DataGrid with paging functionality.
by jayanti surya prakash
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 19012/ 40

Introduction

This article will help you create a DataGrid with customized paging.  This will give you numbers from 1 to 10 in the middle of the DataGrid Header, "Previous" and "Next" buttons on both ends of the DataGrid Header and another link button like ".." (Only from 2nd page) which will take the user to the previous 10 records.

Requirement

.NET Framework 1.1

Create an ASP.NET page with the code as given in listing 1

ASP.NET Page Code

Listing 1

<HTML>
<HEAD>
<title>PagedDataGrid</title>
<meta name="GENERATOR"content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE"content="Visual Basic .NET 7.1">
<meta name="vs_defaultClientScript"content="JavaScript">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
<SCRIPT LANGUAGE="javascript"> 
  function getSelectedValue(paramSelectedValue)
  {
    document.Form1.hdnSelectedValue.value =paramSelectedValue;               
  }
  function showLoad()
  {
   document.Form1.hdnShow.value = 'Y';                                        
  }               
</SCRIPT>
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="Form1"method="post" runat="server">
<TABLE width="100%">
<tr>
<td align="left"
width="5%"><asp:linkbutton id="lnkPrev"
CssClass="clsPagestyle" Runat="server"
Visible="True" Enabled="True"
Font-Underline="False"><span><<</span>Prev</asp:linkbutton></td>
<td align="center"
width="90%"><asp:panel id="pnlNumber"
CssClass="clsPagestyle" Visible="True"
Runat="server"></asp:panel></td>
<td align="right"
width="5%"><asp:linkbutton id="lnkNext"
CssClass="clsPagestyle" Runat="server"
Visible="True" Enabled="True"
Font-Underline="False">Next>></asp:linkbutton></td>
</tr>
<tr>
<td width="100%"colspan="3">                         
<asp:DataGrid id="dgIFA"
runat="server" Width="100%" Height="248px"
AllowCustomPaging="True" AllowPaging="True">
<PagerStyle Visible="False"Position="Top" Mode="NumericPages"></PagerStyle>
</asp:DataGrid>
</td>
</tr>
</TABLE>
<INPUT id="hdnSelectedValue"type="hidden" name="hdnSelectedValue"RUNAT="server">
<INPUT id="hdnShow" type="hidden"name="hdnShow" RUNAT="server">
</form>
</body>
</HTML>

Visual Basic .NET Code

After adding the above code, create a Visual Basic .NET code behind file and add the code in Listing 2.  If you are using Visual Studio .NET 2003 to create projects, double-click anywhere on the design area and add the code given below.

Listing 2

Dim ObjDataSet As New DataSet
<System.Diagnostics.DebuggerStepThrough()> 
Private Sub InitializeComponent()
End Sub
 
Protected WithEvents dgIFA AsSystem.Web.UI.WebControls.DataGrid
Protected WithEvents hdnSelectedValue AsSystem.Web.UI.HtmlControls.HtmlInputHidden
Protected WithEvents lnkPrev AsSystem.Web.UI.WebControls.LinkButton
Protected WithEvents lnkNext AsSystem.Web.UI.WebControls.LinkButton
Protected WithEvents pnlNumber AsSystem.Web.UI.WebControls.Panel
Protected WithEvents hdnShow AsSystem.Web.UI.HtmlControls.HtmlInputHidden
 
Private designerPlaceholderDeclaration AsSystem.Object
 
Private Sub Page_Init(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles MyBase.Init
  InitializeComponent()
End Sub
 
Dim CurrentPage As Integer
Dim dtIFA As New DataTable
Const Page_Count As Integer = 10
Const Record_Count As Integer = 10
Dim dvIFAPage As New DataView
 
Private Sub Page_Load(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles MyBase.Load
 
  If Page.IsPostBack = False Then
    Dim dtDummy As New DataTable
    Dim dc(2) As DataColumn
    Dim dc2(4) As DataColumn
    dc(0) = New DataColumn
    dc(0).ColumnName = "Type"
    dtDummy.Columns.Add(dc(0))
 
    dc(1) = New DataColumn
    dc(1).ColumnName = "Country"
    dtDummy.Columns.Add(dc(1))
 
    dc2(0) = New DataColumn
    dc2(0).ColumnName ="Bank_Company_Name"
    dtDummy.Columns.Add(dc2(0))
 
    dc2(1) = New DataColumn
    dc2(1).ColumnName = "Bank_Account"
    dtDummy.Columns.Add(dc2(1))
 
    dc2(2) = New DataColumn
    dc2(2).ColumnName ="Bank_Company_Name1"
    dtDummy.Columns.Add(dc2(2))
 
    dc2(3) = New DataColumn
    dc2(3).ColumnName = "ID"
    dtDummy.Columns.Add(dc2(3))
 
    ObjDataSet.Tables.Add(dtDummy)
   
    Dim ObjRow As DataRow
    Dim i As Integer
    Dim j As Integer
    For i = 0 To 200
      ObjRow = ObjDataSet.Tables(0).NewRow
      ObjRow("Type"= "Bank"
      ObjRow("Country"= "India"
      ObjRow("Bank_Company_Name"="World Bank"
      ObjRow("Bank_Account"="12345"
      ObjRow("Bank_Company_Name1"="World Bank"
      ObjRow("ID"= (i)
      ObjDataSet.Tables(0).Rows.Add(ObjRow)
    Next
    Cache.Insert("DataTable" & _
Session.SessionID, CType(ObjDataSet.Tables(0), DataTable), Nothing, _
Now.AddHours(1), TimeSpan.Zero)
    dgIFA.DataSource = ObjDataSet
    dgIFA.DataBind()
    Cache.Insert("StrObj", ObjDataSet)
  End If
  lnkNext.Attributes.Add("ONCLICK","javascript:showLoad();")
  lnkPrev.Attributes.Add("ONCLICK","javascript:showLoad();")
  GeneratePageIndex()
  showingGridPage()
  CheckVisibility()
End Sub
 
Private Sub lnkNext_Click(ByVal sender As Object,ByVal e As System.EventArgs) Handles lnkNext.Click
  Try
  If Len(hdnSelectedValue.Value) > 0 Then
    CurrentPage = hdnSelectedValue.Value
  Else
    CurrentPage = 1
  End If
  CurrentPage + = 1
  hdnSelectedValue.Value = CurrentPage
  GeneratePageIndex()
  showingGridPage()
  CheckVisibility()
  Catch ex As Exception
  End Try
End Sub
 
Private Sub lnkPrev_Click(ByVal sender As Object,ByVal e As System.EventArgs) Handles lnkPrev.Click
  Try
  If Len(hdnSelectedValue.Value) > 0 Then
    CurrentPage = hdnSelectedValue.Value
  Else
    CurrentPage = 1
  End If
  CurrentPage - = 1
  hdnSelectedValue.Value = CurrentPage
  GeneratePageIndex()
  showingGridPage()
  CheckVisibility()
  Catch ex As Exception
  End Try
End Sub
 
Function GeneratePageIndex()
  Try
  Dim intPageCount, intIterate, intUBound As Integer
  Dim intStartIdex As Integer = 1
  Dim strSplit As String = String.Empty
  If Len(hdnSelectedValue.Value) > 0 Then
    CurrentPage = hdnSelectedValue.Value
  Else
    CurrentPage = 1
  End If
  dtIFA = CType(Cache.Get("DataTable"& Session.SessionID), DataTable)
  If dtIFA Is Nothing Then
    Exit Function
  End If
 
  intPageCount =System.Math.Ceiling(((dtIFA.Rows.Count/ Page_Count))
  If intPageCount > Page_Count And CurrentPage> Page_Count Then 'And CurrentPage Mod Page_Count = 1 Then
    intStartIdex = CurrentPage - (CurrentPage Mod10) + 1
  End If
  Dim lnkButton2 As LinkButton = New LinkButton
  If intPageCount < (intStartIdex + Page_Count)Then
    intUBound = intPageCount
  Else
    intUBound = (intStartIdex + Page_Count)
  End If
  pnlNumber.Controls.Clear()
  For intIterate = intStartIdex To intUBound
    If intIterate = (intStartIdex + Page_Count) Then
      lnkButton2.Text = "...N" &"  "
      lnkButton2.ID = "lnkButton" &intIterate
      lnkButton2.CssClass = "clsPagestyle"
      lnkButton2.Font.Underline = False
      strSplit = String.Empty
      strSplit = lnkButton2.ID.ToString()
      strSplit =strSplit.Substring(Len("lnkButton"), Len(strSplit) -Len("lnkButton"))
      lnkButton2.Attributes.Add("ONCLICK","javascript:getSelectedValue(" & strSplit & ");")
      pnlNumber.Controls.Add(lnkButton2)
    ElseIf (intIterate Mod Page_Count) = 1 Then
      Dim lblPages As Label = New Label
      lblPages.Text = "Page(s): "
      lblPages.ID = "lblPages"
      lblPages.CssClass = "clsPagestyle"
      pnlNumber.Controls.Add(lblPages)
 
      If intIterate <> 1 Then
        Dim lnkButton4 As LinkButton = NewLinkButton
        lnkButton4.Text = " ..." &" "
        lnkButton4.ID = "lnkButtonPages"& (intIterate - Page_Count)
        lnkButton4.CssClass ="clsPagestyle"
        lnkButton4.Font.Underline = False
        lnkButton4.Enabled = True
        strSplit = String.Empty
        strSplit = lnkButton4.ID.ToString()
        strSplit =strSplit.Substring(Len("lnkButtonPages"), Len(strSplit) -Len("lnkButtonPages"))
        lnkButton4.Attributes.Add("ONCLICK","javascript:getSelectedValue(" & strSplit & ");")
        pnlNumber.Controls.Add(lnkButton4)
      End If
  
      Dim lnkButton1 As LinkButton = New LinkButton
      lnkButton1.Text = intIterate & " "
      lnkButton1.ID = "lnkButton" &intIterate
      lnkButton1.CssClass = "clsPagestyle"
      lnkButton1.Font.Underline = False
      strSplit = String.Empty
      strSplit = lnkButton1.ID.ToString()
      strSplit =strSplit.Substring(Len("lnkButton"), Len(strSplit) -Len("lnkButton"))
      lnkButton1.Attributes.Add("ONCLICK","javascript:getSelectedValue(" & strSplit & ");")
      If CurrentPage Mod Page_Count = 1 Then
        lnkButton1.Enabled = False
      Else
        lnkButton1.Enabled = True
      End If
      pnlNumber.Controls.Add(lnkButton1)
    Else
      Dim lnkButton3 As LinkButton = New LinkButton
      lnkButton3.Text = intIterate & " "
      lnkButton3.ID = "lnkButton" &intIterate
      lnkButton3.CssClass = "clsPagestyle"
      lnkButton3.Font.Underline = False
      strSplit = String.Empty
      strSplit = lnkButton3.ID.ToString()
      strSplit =strSplit.Substring(Len("lnkButton"), Len(strSplit) -Len("lnkButton"))
      lnkButton3.Attributes.Add("ONCLICK","javascript:getSelectedValue(" & strSplit & ");")
      If CurrentPage = intIterate Then
        lnkButton3.Enabled = False
      Else
        lnkButton3.Enabled = True
      End If
      pnlNumber.Controls.Add(lnkButton3)
    End If
  Next
  Catch ex As Exception
  End Try
End Function
 
Function showingGridPage()
  Try
  dtIFA = CType(Cache.Get("DataTable"& Session.SessionID), DataTable)
  If dtIFA Is Nothing Then
    Exit Function
  End If
  If Len(hdnSelectedValue.Value) > 0 Then
    CurrentPage = hdnSelectedValue.Value
  Else
    CurrentPage = 1
  End If
  'CheckBoxSelected()
  If CurrentPage > 0 Then
    Dim strCondition As String
    strCondition = "ID >= " &(CurrentPage - 1) * Record_Count & " and " & "ID <" & (CurrentPage) * Record_Count
    dvIFAPage = New DataView(dtIFA, strCondition,"", DataViewRowState.CurrentRows)
    Cache.Insert("DataView" &Session.SessionID, dvIFAPage, NothingNow.AddHours(1), TimeSpan.Zero)
    dgIFA.DataSource = dvIFAPage
    dgIFA.DataBind()
   
  End If
  Catch ex As Exception
  End Try
End Function
 
Function CheckVisibility()
  Try
  dtIFA = CType(Cache.Get("DataTable"& Session.SessionID), System.Data.DataTable)
  If dtIFA Is Nothing Then
    lnkNext.Visible = False
    lnkPrev.Visible = False
    Exit Function
  Else
    lnkNext.Visible = True
    lnkPrev.Visible = True
  End If
 
  If (System.Math.Ceiling(((dtIFA.Rows.Count) /Page_Count)) <= 1) Then
    lnkNext.Enabled = False
    lnkPrev.Enabled = False
  ElseIf CurrentPage >=System.Math.Ceiling(((dtIFA.Rows.Count/ Page_Count)) Then
    lnkNext.Enabled = False
    lnkPrev.Enabled = True
  ElseIf (CurrentPage = 1) Then
    lnkNext.Enabled = True
    lnkPrev.Enabled = False
  Else
    lnkNext.Enabled = True
    lnkPrev.Enabled = True
  End If
  Catch ex As Exception
 
  End Try
End Function

The core of the above application is three server side functions, namely GeneratePageIndex, showingGridPage and CheckVisibility.  GeneratePageIndex method generates the page numbers.  The showingGridPage() function will show the data relating to the page number clicked.  CheckVisibility() manages the visibility elements, such as the  "Previous" button should be disabled in the first page and the "Next" button should be disabled in the last page.

In the page load event we will call these methods to formulate the customizing of the page indexes in a DataGrid.  After implementing the above code your grid will look like below.

Final Output

Figure 1

Downloads

[Download Sample]

Summary

With the help of this code snippet, you have learned how to customize a DataGrid.



User Comments

Title: Customized DataGrid Paging   
Name: Keyur Raval
Date: 2008-03-19 8:09:57 AM
Comment:
Good one , but another shortcut available?
Title: THX   
Name: Uter
Date: 2007-01-19 7:35:20 AM
Comment:
Thanks for this code!!!! It is good one
Title: Customized DataGrid Paging   
Name: Bala
Date: 2006-06-13 3:06:51 AM
Comment:
Good program, if there is a sort option by clicking the grid columns would be useful
Title: Customized Datagrid Paging   
Name: Pooja Sharma
Date: 2006-06-10 3:16:15 AM
Comment:
It was great,i'ld rank it with 5 points.
Title: Thanks for this document   
Name: Edwill dos Santos Paiva
Date: 2006-06-08 3:00:20 PM
Comment:
Very Good !!! I WAS GREAT !!!!
Title: Customized DataGrid Paging   
Name: Sailaja
Date: 2006-05-10 6:10:35 AM
Comment:
It is good one
Please keep an excel sheet option also so that they can load the whole data at once

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2017 ASPAlliance.com  |  Page Processed at 2017-03-24 1:58:10 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search