The following code snippet demonstrates how to setup paging for a GridView contol using the PageIndexChanging event.
// Default.aspx
<%@ 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></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="Contacts" runat="server" OnPageIndexChanging="PageIndexChanging" AllowPaging="true" PageSize=10 />
</div>
</form>
</body>
</html>
// Default.aspx.cs
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;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.BindGridView();
}
private void BindGridView()
{
string provider = @"Data Source=_DATA_SOURCE_HERE_;Initial Catalog=AdventureWorks;Integrated Security=True";
SqlConnection con = new SqlConnection(provider);
try
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT TOP 50 FirstName, MiddleName, LastName, EmailAddress FROM Person.Contact", con);
DataTable table = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(table);
Contacts.DataSource = table;
Contacts.DataBind();
}
catch ( Exception ex)
{
Response.Write(ex.Message);
}
}
protected void PageIndexChanging(object sender, GridViewPageEventArgs e)
{
Contacts.PageIndex= e.NewPageIndex;
Contacts.DataBind();
}
}