Just copy and paste this code into a new blank page. Change the Database name, UID and password. It uses the Northwind database with SQL Server and save it as a ‘.aspx’ page.
To make it “Next-Previous” instead of numbering – change the PagerStyle-Mode to:
PagerStyle-Mode=’NextPrev’
PagerStyle-NextPageText=’Next ->’
PagerStyle-PrevPageText=”<- Previous”
<%@ Import Namespace=”System.Data” %>
<%@ Import Namespace=”System.Data.SQLClient” %>
<script runat=”server” language=”VB”>
Protected SQLStmt As String = “SELECT CompanyName, ContactName, ContactTitle, Phone, Fax FROM Customers”
Sub Page_Load(Source As Object, E As EventArgs)
If Not Page.IsPostBack Then
SQLStatement.Text = SQLStmt
BindData()
End If
End Sub
Sub BindData()
Dim myDataSet As New DataSet
Dim myDataSetCommand As SQLDataAdapter
Dim ConString As String
ConString =”server=localhost;database=Northwind;uid=UserName;pwd=Userpassword;”
myDataSetCommand = New SQLDataAdapter(SQLStatement.Text, ConString)
myDataSetCommand.fill(myDataSet, “Customers”)
myDataGrid.DataSource = myDataSet.Tables(“Customers”).DefaultView
myDataGrid.DataBind()
End Sub
Sub PageIndexChanged_OnClick(Source As Object, E As DataGridPageChangedEventArgs)
MyDataGrid.CurrentPageIndex = e.NewPageIndex
BindData()
End Sub
Sub SortCommand_OnClick(Source As Object, E As DataGridSortCommandEventArgs)
SQLStatement.Text = SQLStmt & ” ORDER BY ” & E.SortExpression
BindData()
End Sub
</script>
<style>
.DataGrid {font:x-small Verdana, Arial, sans-serif}
</style>
<title>ASPExpress.com – Paging AND Sorting in the DataGrid</title>
</head>
<body>
<div align=”center”>Paging And Sorting Together with ASP.Net </div>
<form runat=”server” method=”post”>
<asp:DataGrid runat=”server” id=”myDataGrid”
borderwidth=”5″
bordercolor=”black”
Borderstyle=”double”
PagerStyle-VerticalAlign=”top”
Cellpadding=”4″
Cellspacing=”0″
ShowHeader=”True”
CssClass=”DataGrid”
HeaderStyle-ForeColor=”Black”
HeaderStyle-Font-Bold=”True”
AllowSorting=”True”
OnSortCommand=”SortCommand_OnClick”
AllowPaging=”True”
OnPageIndexChanged=”PageIndexChanged_OnClick”
PageSize=”10″
width=”100%”
HeaderStyle-BackColor=”#aaaadd”
AlternatingItemStyle-BackColor=”#eeeeee”
PagerStyle-Backcolor=”#aaaadd”
PagerStyle-Forecolor=”Black”
PagerStyle-HorizontalAlign=”center”
PagerStyle-Mode=”NumericPages”
PagerStyle-BorderStyle=”Inset”
/>
</form>
<asp:Label id=”SQLStatement” runat=”server” Visible=”false” />
</body>
</html>