Sorting , Paging and AutoGenerateColumns

The GridView control provides many built-in capabilities that allow the user to sort, update, delete, select, and page through items in the control.

Gridview paging sorting

Download Database

In this article I have used Microsoft's Pubs database for sample data. You can download it free from the following link.


Before you start to generate GridView in your asp file, you should create a ConnectionString in your web.Config File. Double click the web.config file on the right hand side of the Visual Studio and add the following connectionstring code in that file.

web.config file

Web.Config File

<?xml version="1.0"?> <configuration> <connectionStrings> <add name="SQLDbConnection" connectionString="Server=Your-Server-Name; Database=pubs; User Id=sa; password= your-passoword" providerName="System.Data.SqlClient" /> </connectionStrings> </configuration>

Each column in the GridView control is represented by a DataControlField object. By default, the AutoGenerateColumns property is set to true, You can also manually control which column fields appear in the GridView control by setting the AutoGenerateColumns property to false .


Sorting allows the user to sort the items in the GridView control with respect to a specific column by clicking on the column's header. To enable sorting, set the AllowSorting property to true.


Instead of displaying all the records in the data source at the same time, the GridView control can automatically break the records up into pages. To enable paging, set the AllowPaging property to true.


Also we can set how many rows we want to see in a page.


The following ASP.NET program shows how to enable sorting and paging in a GridView with a custom defined column fields.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> <html xmlns=""> <head id="Head1" runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowSorting="True" DataSourceID="SqlDataSource1" AllowPaging="True" PageSize="4"> <Columns> <asp:BoundField ReadOnly="True" HeaderText="stor_id" DataField="stor_id" SortExpression="stor_id"></asp:BoundField> <asp:BoundField HeaderText="stor_name" DataField="stor_name" SortExpression="stor_name"></asp:BoundField> <asp:BoundField HeaderText="stor_address" DataField="stor_address" SortExpression="stor_address"></asp:BoundField> <asp:BoundField HeaderText="city" DataField="city" SortExpression="city"></asp:BoundField> <asp:BoundField HeaderText="state" DataField="state" SortExpression="state"></asp:BoundField> <asp:BoundField HeaderText="zip" DataField="zip" SortExpression="zip"></asp:BoundField> </Columns> </asp:GridView> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:SQLDbConnection %>" SelectCommand="select * from stores" /> </div> </form> </body> </html>