Sample code for ASP.NET DataGrid paging
Here is a sample code for ASP.NET DataGrid paging
The DataGrid control has built-in support for paging through the records of a data source.
For example, there may be a large number of records in the AccountsTable. If we divide the records
into multiple pages, it is convenient for the user to see the data.
We enable paging for a DataGrid by enabling the AllowPaging property and
creating a subroutine to change the current page.
Write the following code in the HTML window
<HTML>
<HEAD>
<title>DatagridPaging</title>
</HEAD>
<body>
<form id=Form1" runat=server>
<asp:DataGrid ID=dgrdAccounts runat=server
AllowPaging=True PageSize=5"
OnPageIndexChanged=drdaccounts_pageIndexChanged
cellpadding=3">
</asp:DataGrid>
</form>
</body>
</HTML>
Write the following code in the Code behind window
Imports System.Data.SqlClient
Dim myConnection As SqlConnection = New SqlConnection(Data Source=SYS1;Integrated Security=SSPI;Initial Catalog=FinAccounting)
Const strSQL As String = SELECT AccountCode,Accountname,AccountDescription FROM AccountsTable
Dim myDataAdapter As SqlDataAdapter = New SqlDataAdapter(strSQL, myConnection)
Dim dstaccounts As New DataSet()
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Not IsPostBack() Then
BindDataGrid()
End If
End Sub
Sub BindDataGrid()
myConnection.Open()
myDataAdapter.Fill(dstaccounts, AccountsTable)
dgrdAccounts.DataSource = dstaccounts
dgrdAccounts.DataBind()
End Sub
Sub drdaccounts_pageIndexChanged(ByVal s As Object, ByVal e As DataGridPageChangedEventArgs)
dgrdAccounts.CurrentPageIndex = e.NewPageIndex
BindDataGrid()
End Sub
This example displays five records at a time from the AccountsTable. By clicking the
< and > links displayed at the bottom of the DataGrid,
we can navigate forward or backward. A new page is selected
with the drdaccounts_pageIndexChanged subroutine.
This subroutine assigns the value of the NewPageIndex to the DataGrid controls CurrentPageIndex.
The subroutine then rebinds the DataGrid to the data source, displaying the new page of records.
Regards
bhar

