This tutorial will show you how to display data using the .NET GridView Control, stored procedures, ASP.NET 2.0 and C#.NET

Querying an SQL database with stored procedures using C# .NET is easy to do.

First, you will need to import the System.Data.SqlClient namespace.

The System.Data.SqlClient namespace contains the SqlCommand and SqlConnection classes that we need in order to connect to our database and to send an SQL command to it.

We’ll put our code in the Page_Load() event.

When the Page_Load() event fires, a new SqlCommand object is instantiated with our connection string and our stored procedure name. We add the parameters needed for the stored procedure by using our SqlCommand object’s Parameters.Add() method.

Afterwards, we will attempt to connect using the Open() method of our cmd.Connection object. Once it is connected we will attempt to execute the stored procedure we specified earlier (in this example CustOrderHist stored procedure in the Northwind db).

If all goes well, we will have the results of our SQL query assigned to the gvwExample’s DataSource property. Now all we have to do is call the DataBind() method of our gvwExample to bind the data to the control. The data is now ready to be displayed.

We have to add a few tags on the front end of the .aspx page to place where we want the GridView control to display its bound data. We also specify what part of the data from the data set we would like to display. The front end .aspx page looks something like this:

The flow for the code behind page is as follows.

Download Source Files