Note: To test samples, I'll use the Northwind database
To test this application, create an ASP.NET Web application and add a DataGrid
control to the Web form from the toolbox.
Enabling Paging at Design-Time
You can set paging options at design-time by right-clicking on the DataGrid's
properties menu item. The paging page looks like figure 7-48. This page lets you
set the number of rows per page and the type of navigation you want to show. If
you want to provide your own paging click on the Allow Custom Paging check box.
Figure 7-48. DataGrid paging properties
As you can see from figure 7-48, I set the page size to 5 rows and mode to page
Numbers. So, when a browser displays the first page of a table in the DataGrid,
it will show five rows. Additionally, it will display page numbers at the button
of the page so that users can navigate through the pages. The next step for
enabling paging in a data grid is to write a PageIndexChanged event handler. You
can add the PageIndexChanged handler from the data grid's properties windows, as
shown in figure 7-49.
Figure 7-49. Adding the PageIndexChanged event handler
Now write the code shown in listing 7-10. As you can see, I set
DataGrid.CurrentPageIndex as DataGridPageChangedEventArgs's NewPageIndex. VS.NET
takes cure of the rest for you.
Listing 7-10. The PageIndexChanged handler of the data grid control
protected void
Page_Load(object sender,
System.Web.UI.WebControls.DataGridPageChangedEventArgs
e)
{
// Create a
Connection object
string ConnectionString =
@"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source =c://GuestBook.mdb";
OleDbConnection conn =
new OleDbConnection(ConnectionString);
// open the
connection
if (conn.State !=
ConnectionState.Open)
conn.Open();
// Create a data
adapter
OleDbDataAdapter da =
new
OleDbDataAdapter
("SELECT ID,Name,Address,Email FROM
Guest", conn);
// Create and fill a
dataset
DataSet ds =
new DataSet();
da.Fill(ds);
// Bind dataset to
the control
DataGrid1.DataSource = ds;
DataGrid1.DataBind();
// Close the
connection
if (conn.State ==
ConnectionState.Open)
conn.Close();
}
Now if you run the program, you'll see that the first page looks like figure
7-50.
Figure 7-50. Paging in the DataGrid
As you can see from Figure 7-50, there are five rows displayed in the grid and
there are two pages available. If you click on the 2 link, the result looks like
figure 7-51.
Figure 7-51. The second page of DataGrid paging sample
Conclusion