In this article I will explain with an example, how to perform select, insert, edit, update, delete in
GridView using a single
Stored Procedure in ASP.Net using C# and VB.Net.
This process is also known as CRUD i.e. Create, Read, Update and Delete in
GridView using
Stored Procedure with
SQL Server database in ASP.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.
HTML Markup
The HTML Markup consists of following controls:
GridView – For displaying data.
Columns
The GridView consists of two TemplateField columns and a CommandField column.
TemplateField – The TemplateField column consists of ItemTemplate and EditItemTemplate.
ItemTemplate – The ItemTemplate contains a Label.
EditItemTemplate – The EditItemTemplate contains a TextBox.
The GridView has been assigned with following properties:
DataKeyNames – For permitting to set the names of the Column Fields, that we want to use in code but do not want to display it. Example Primary Keys, ID fields, etc.
EmptyDataText – For displaying text when there is no data in the GridView.
The GridView has been assigned with the following event handlers i.e. OnRowDataBound, OnRowEditing, OnRowCancelingEdit, OnRowUpdating and OnRowDeleting.
TextBox – For capturing records to be added.
Button – For adding records.
The Button has been assigned with an OnClick event handler.
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false" DataKeyNames="CustomerId"
OnRowDataBound="OnRowDataBound" OnRowEditing="OnRowEditing" OnRowCancelingEdit="OnRowCancelingEdit"
OnRowUpdating="OnRowUpdating" OnRowDeleting="OnRowDeleting" EmptyDataText="No records has been added.">
<Columns>
<asp:TemplateField HeaderText="Name" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%# Eval("Name") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Country" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCountry" runat="server"Text='<%# Eval("Country") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Link" ShowEditButton="true" ShowDeleteButton="true" ItemStyle-Width="150" />
</Columns>
</asp:GridView>
<table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse">
<tr>
<td style="width: 150px">Name:<br />
<asp:TextBox ID="txtName" runat="server" Width="140" />
</td>
<td style="width: 150px">Country:<br />
<asp:TextBox ID="txtCountry" runat="server" Width="140" />
</td>
<td style="width: 100px">
<asp:Button runat="server" ID="btnAdd" Text="Add" OnClick="Insert" />
</td>
</tr>
</table>
Stored Procedure for Select, Insert, Update and Delete
The following
Stored Procedure will be used to perform Select, Insert, Update and Delete operations on the
SQL Server database table.
CREATE PROCEDURE [Customers_CRUD]
@Action VARCHAR(20)
,@CustomerId INT = NULL
,@Name VARCHAR(100) = NULL
,@Country VARCHAR(50) = NULL
AS
BEGIN
SET NOCOUNT ON;
--SELECT
IF @Action = 'SELECT'
BEGIN
SELECT [CustomerId]
,[Name]
,[Country]
FROM [Customers]
END
--INSERT
IF @Action = 'INSERT'
BEGIN
INSERT INTO [Customers]
([Name]
,[Country])
VALUES (@Name
,@Country)
END
--UPDATE
IF @Action = 'UPDATE'
BEGIN
UPDATE [Customers]
SET [Name] = @Name
,[Country] = @Country
WHERE [CustomerId] = @CustomerId
END
--DELETE
IF @Action = 'DELETE'
BEGIN
DELETE FROM [Customers]
WHERE [CustomerId] = @CustomerId
END
END
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
Binding the GridView with records from SQL Server Database Table
Inside the Page_Load event handler, the BindGrid method is called where the value of Action is added as parameter to SqlCommand object.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string spName = "Customers_CRUD";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(spName, con))
{
cmd.Parameters.AddWithValue("@Action", "SELECT");
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
cmd.CommandType = CommandType.StoredProcedure;
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
Me.BindGrid()
End If
End Sub
Private Sub BindGrid()
Dim spName As String = "Customers_CRUD"
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand(spName, con)
cmd.Parameters.AddWithValue("@Action", "SELECT")
Using sda As New SqlDataAdapter(cmd)
cmd.CommandType = CommandType.StoredProcedure
Using dt As New DataTable()
sda.Fill(dt)
gvCustomers.DataSource = dt
gvCustomers.DataBind()
End Using
End Using
End Using
End Using
End Sub
Insert
When the
Add button is clicked, the
name and the
country values are fetched from their respective
TextBoxes and are inserted into the
SQL Server database using
Stored Procedure with
Action parameter value as “INSERT”.
Finally, the GridView is populated using the BindGrid method which in-turn refreshes the GridView with updated records.
C#
protected void Insert(object sender, EventArgs e)
{
string spName = "Customers_CRUD";
string name = txtName.Text;
string country = txtCountry.Text;
txtName.Text = string.Empty;
txtCountry.Text = string.Empty;
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(spName, con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Action", "INSERT");
cmd.Parameters.AddWithValue("@Name", name);
cmd.Parameters.AddWithValue("@Country", country);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
this.BindGrid();
}
VB.Net
Protected Sub Insert(sender As Object, e As EventArgs)
Dim spName As String = "Customers_CRUD"
Dim name As String = txtName.Text
Dim country As String = txtCountry.Text
txtName.Text = String.Empty
txtCountry.Text = String.Empty
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand(spName, con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("@Action", "INSERT")
cmd.Parameters.AddWithValue("@Name", name)
cmd.Parameters.AddWithValue("@Country", country)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
Me.BindGrid()
End Sub
Edit
When the Edit button is clicked, the GridView’s OnRowEditing event handler is triggered. Here simply the EditIndex of the GridView is updated with the Row Index of the GridView Row to be edited.
C#
protected void OnRowEditing(object sender, GridViewEditEventArgs e)
{
gvCustomers.EditIndex = e.NewEditIndex;
this.BindGrid();
}
VB.Net
Protected Sub OnRowEditing(sender As Object, e As GridViewEditEventArgs)
gvCustomers.EditIndex = e.NewEditIndex
Me.BindGrid()
End Sub
Update
When the Update button is clicked, the GridView’s OnRowUpdating event handler is triggered.
Inside the
OnRowUpdating event handler, the
CustomerId (primary key) is fetched from the
DataKey property of
GridView while the
Name and
Country fields are fetched from their respective
TextBoxes and are passed to the
Stored Procedure with
Action parameter value as “UPDATE” and the record is updated in the database.
Finally, the GridView is populated using the BindGrid method which in-turn refreshes the GridView with updated records.
C#
protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e)
{
string spName = "Customers_CRUD";
GridViewRow row = gvCustomers.Rows[e.RowIndex];
int customerId = Convert.ToInt32(gvCustomers.DataKeys[e.RowIndex].Values[0]);
string name = (row.FindControl("txtName") as TextBox).Text;
string country = (row.FindControl("txtCountry") as TextBox).Text;
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(spName, con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Action", "UPDATE");
cmd.Parameters.AddWithValue("@CustomerId", customerId);
cmd.Parameters.AddWithValue("@Name", name);
cmd.Parameters.AddWithValue("@Country", country);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
gvCustomers.EditIndex = -1;
this.BindGrid();
}
VB.Net
Protected Sub OnRowUpdating(sender As Object, e As GridViewUpdateEventArgs)
Dim spName As String = "Customers_CRUD"
Dim row As GridViewRow = gvCustomers.Rows(e.RowIndex)
Dim customerId As Integer = Convert.ToInt32(gvCustomers.DataKeys(e.RowIndex).Values(0))
Dim name As String = TryCast(row.FindControl("txtName"), TextBox).Text
Dim country As String = TryCast(row.FindControl("txtCountry"), TextBox).Text
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand(spName, con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("@Action", "UPDATE")
cmd.Parameters.AddWithValue("@CustomerId", customerId)
cmd.Parameters.AddWithValue("@Name", name)
cmd.Parameters.AddWithValue("@Country", country)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
gvCustomers.EditIndex = -1
Me.BindGrid()
End Sub
Cancel Edit
When the Cancel button is clicked, the GridView’s OnRowCancelingEdit event handler is triggered. Here the EditIndex is set to -1 and the GridView is populated with data.
C#
protected void OnRowCancelingEdit(object sender, EventArgs e)
{
gvCustomers.EditIndex = -1;
this.BindGrid();
}
VB.Net
Protected Sub OnRowCancelingEdit(sender As Object, e As EventArgs)
gvCustomers.EditIndex = -1
Me.BindGrid()
End Sub
Delete
When the Delete button is clicked, the GridView’s OnRowDeleting event handler is triggered.
Inside the
OnRowDeleting event handler, the
CustomerId (primary key) is fetched from the DataKey property of
GridView and is passed to the
Stored Procedure along with the
Action parameter value as “DELETE”.
Finally, the GridView is populated using the BindGrid method which in-turn refreshes the GridView with updated records.
C#
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
string spName = "Customers_CRUD";
int customerId = Convert.ToInt32(gvCustomers.DataKeys[e.RowIndex].Values[0]);
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(spName, con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Action", "DELETE");
cmd.Parameters.AddWithValue("@CustomerId", customerId);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
this.BindGrid();
}
VB.Net
Protected Sub OnRowDeleting(sender As Object, e As GridViewDeleteEventArgs)
Dim spName As String = "Customers_CRUD"
Dim customerId As Integer = Convert.ToInt32(gvCustomers.DataKeys(e.RowIndex).Values(0))
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand(spName, con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("@Action", "DELETE")
cmd.Parameters.AddWithValue("@CustomerId", customerId)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
Me.BindGrid()
End Sub
Delete Confirmation Message
The delete operation will be confirmed using
JavaScript Confirmation Box, thus inside the
OnRowDataBound event handler, the
Delete LinkButton is assigned with a
JavaScript onclick event handler.
C#
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != gvCustomers.EditIndex)
{
(e.Row.Cells[2].Controls[2] as LinkButton).Attributes["onclick"] = "return confirm('Do you want to delete this row?');";
}
}
VB.Net
Protected Sub OnRowDataBound(sender As Object, e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow AndAlso e.Row.RowIndex <> gvCustomers.EditIndex Then
TryCast(e.Row.Cells(2).Controls(2), LinkButton).Attributes("onclick") = "return confirm('Do you want to delete this row?');"
End If
End Sub
Screenshot
Downloads