Create a SqlConnection and a SqlDataAdapter member: Drag a table from the Server Explorer into the WebForm design surface. This will create a SqlConnection and a SqlDataAdapter member in the web form. Give these members names that make sense. This is one of the quickest ways to create a SqlDataAdapter with simple select, insert, delete and update capabilities. In this article, we will only use the select capability. In the next article of this series, we will also make use the delete and update capabilities.

Add a DataGrid Control: Drag a DataGrid control from the tool box into the WebForm design surface. Enable sorting by setting the AllowSorting property to True and enable paging by setting the AllowPaging property to True.

Add code to respond to the Page_Load, DataGrid SortCommand and DataGridProducts PageIndexChanged events. The code behind the page will look like:

The bindGrid function is the function that creates the data source and binds it to the DataGrid.

The code in the Page_Load event will populate the DataGrid when the page is initially accessed. The line, if (!this.IsPostBack), will prevent the bindGrid function from getting called multiple times in a post-back situation such as sorting or paging.

The code in the SortCommand and PageIndexChanged event handlers are responsible for sorting and paging the data. In the code, we also added the functionality alternate the sort direction on subsequent click of the same column header.

Note that the code in the three event handlers is rather generic; the knowledge of the data source is fully contained in the bindGrid function. Therefore, the repetitive code in these three event handlers could be reused by moving it to a control. We will examine how to do this in the next section.