In this article I will explain with an example, how to execute
Stored Procedure and get results from
SQL Server Database in ASP.Net using C# and VB.Net.
Database
I have made use of the following table Customers with the schema as follows.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
Stored Procedure
CREATE PROCEDURE [Customers_GetCustomers]
AS
BEGIN
SET NOCOUNT ON;
SELECT [CustomerId]
,[Name]
,[Country]
FROM [Customers]
END
HTML Markup
The HTML Markup consists of following control:
GridView – For displaying data.
The GridView consists of three BoundFIeld columns.
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="CustomerId" HeaderText="Customer Id" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Country" HeaderText="Country" />
</Columns>
</asp:GridView>
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Executing Stored Procedure in C# and VB.Net
Inside the Page_Load event handler, first the connection is read from Web.Config file.
Then, a connection to the database is established using
SqlConnection class and
CommandType is specified as
Stored Procedure using
SqlCommand class object.
The SqlDataAdapter object is initialized and using the Fill function, the DataTable is populated with the records from the database.
Finally, the DataTable is assigned to the GridView and the GridView is populated with records.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string spName = "Customers_GetCustomers";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(spName, con))
{
cmd.CommandType = CommandType.StoredProcedure;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
gvCustomers.DataSource = dt;
gvCustomers.DataBind();
}
}
}
}
}
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim spName As String = "Customers_GetCustomers"
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand(spName, con)
cmd.CommandType = CommandType.StoredProcedure
Using sda As New SqlDataAdapter(cmd)
Using dt As New DataTable()
sda.Fill(dt)
gvCustomers.DataSource = dt
gvCustomers.DataBind()
End Using
End Using
End Using
End Using
End If
End Sub
Screenshots
DataTable
GridView
Downloads