Categories
CSharp

Display result of a stored procedure in a GridView

This tutorial will tell you how to display data into a Grid View using a stored procedure.

Before using the code below you need to have the following:

1. SQL stored procedure (in the below example I have created a stored procedure named myStoredProcedure)

2. Add a gridView control to the page.

The code below is pretty much simple and self-explanatory, please feel free to writeIn if you have any doubts.

string storedProcedureName = "myStoredProcedure";
string connectionString = "XXX";

var connection = new SqlConnection(connectionString);
var command = new SqlCommand(storedProcedureName, connection);

command .CommandType = CommandType.StoredProcedure;
command .Parameters.Add("myID", "someValueToBePassed");

try
{
	connection.Open();
	gridView.DataSource = command.ExecuteReader();
	gridView.DataBind();
}
catch (Exception)
{
	throw; 
}
finally
{
	connection.Close();
	command.Dispose();
}