In this post, I will explain GridView CRUD operations: Select, Insert, Edit, Update, and Delete using a single stored procedure with alert confirmations on delete from GridView.
I have a GridView where I want to perform insert, update, delete, and edit operations. Additionally, I want to enable deletion of records from the GridView by clicking on the delete button with an alert message 'Are you sure you want to delete?'
To achieve all these functionalities, I have utilized GridView events.
Create a table in sql sever.
CREATE TABLE [dbo].[tbluser](
[Userid] [int] IDENTITY(1,1) NOT NULL,
[Username] [varchar](100) NULL,
[password] [varchar](100) NULL,
[Address] [varchar](100) NULL
)
I have created a stored procedure for performing insert, update, delete, and edit operations. I have declared a @status parameter, and accordingly, we will perform the database operation.
As seen in the below query, I have declared nullable parameters in the stored procedure, i.e., optional parameters. If you are not familiar with the stored procedure, please read this post first.-what is Stored Procedure?
create PROCEDURE Crudoperation
@userid int=null,
@username varchar(100)=null,
@password varchar(100)=null,
@address varchar(100)=null,
@status varchar(50)=null
as
begin
if(@status='select')
begin
select * from tbluser
end
if(@status='update')
begin
update tbluser set password=@password,Address=@address where UserId=@userid
end
if(@status='delete')
begin
delete from tbluser where UserId=@userid
end
if(@status='insert')
begin
insert into tbluser(UserName,password,Address) values(@username,@password,@address)
end
end
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowCommand="GridView1_RowCommand" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating">
</asp:GridView>
</div>
</form>
</body>
</html>
Event are created on codebehid of page.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
}
}
now paste the following code between gridview view tag.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:GridView ID="GridView1" runat="server" DataKeyNames="UserId,UserName" AutoGenerateColumns="False" Showfooter="True" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowCommand="GridView1_RowCommand" OnRowUpdating="GridView1_RowUpdating" CellPadding="4" ForeColor="#333333" GridLines="None" > <AlternatingRowStyle BackColor="White" /> <Columns> <asp:TemplateField HeaderText="Action"> <EditItemTemplate> <asp:Button ID="btnUpdate" CommandName="Update" runat="server" ToolTip="Update" Height="30px" Width="60px" Text="Update" /> <asp:Button ID="btnCancel" CommandName="Cancel" runat="server" Text="Cancel" ToolTip="Cancel" Height="30px" Width="60px" /> </EditItemTemplate> <ItemTemplate> <asp:Button ID="btnEdit" runat="server" CommandName="Edit" Text="Edit" ToolTip="Edit" Height="30px" Width="60px"/> <asp:Button ID="btnDelete" runat="server" Text="Delete" CommandName="Delete" ToolTip="Delete" Height="30px" Width="60px" OnClientClick="return confirm('Are you sure you want to delete this ?');" /> </ItemTemplate> <FooterTemplate> <asp:Button ID="btnAdd" runat="server" Text="AddNew" CommandName="AddNew" Width="120px" Height="30px" ToolTip="Add new User"/> </FooterTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Username"> <EditItemTemplate> <asp:Label ID="lbleditusr" runat="server" Text='<%#Eval("Username") %>'/> </EditItemTemplate> <ItemTemplate> <asp:Label ID="lblitemUsr" runat="server" Text='<%#Eval("Username") %>'/> </ItemTemplate> <FooterTemplate> <asp:TextBox ID="txtftrusrname" runat="server"/> </FooterTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="password"> <EditItemTemplate> <asp:TextBox ID="txtpassword" runat="server" Text='<%#Eval("password") %>'/> </EditItemTemplate> <ItemTemplate> <asp:Label ID="lblpassword" runat="server" Text='<%#Eval("password") %>'/> </ItemTemplate> <FooterTemplate> <asp:TextBox ID="txtftrpassword" runat="server"/> </FooterTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Address"> <EditItemTemplate> <asp:TextBox ID="txtAddress" runat="server" Text='<%#Eval("Address") %>'/> </EditItemTemplate> <ItemTemplate> <asp:Label ID="lblAddress" runat="server" Text='<%#Eval("Address") %>'/> </ItemTemplate> <FooterTemplate> <asp:TextBox ID="txtftrAddress" runat="server"/> </FooterTemplate> </asp:TemplateField> </Columns> <EditRowStyle BackColor="#2461BF" /> <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" /> <RowStyle BackColor="#EFF3FB" /> <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" /> <SortedAscendingCellStyle BackColor="#F5F7FB" /> <SortedAscendingHeaderStyle BackColor="#6D95E1" /> <SortedDescendingCellStyle BackColor="#E9EBEF" /> <SortedDescendingHeaderStyle BackColor="#4870BE" /> </asp:GridView> </div> </form> </body> </html>
Eval function is used to bind data from database to controls inside DataBound controls like GridView, Repeater, etc.
now your gridview should look like this
The DataKeyNames property allows us to set the names of the column fields in a GridView that we want to use in our code but do not want to display. For example, primary keys, IDs, or usernames.
In my example, I don't want to display the UserID, but I want to use it in the code-behind for deleting and updating records.
IsPostBack is a property of the ASP.NET page that checks whether the page is being loaded for the first time or if it is being loaded due to a button click on the page. Now, I have written code for operations on the event of the GridView.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ToString());
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
userDetails(); //check page is loaded first time or it's loaded due to button on page
}
}
public void userDetails()
{
con.Open();
SqlCommand cmd = new SqlCommand("Crudoperation", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@status", "select");
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
else
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow()); // if record not found then returning a blank table structure
GridView1.DataSource = ds;
GridView1.DataBind();
int columncount = GridView1.Rows[0].Cells.Count;
GridView1.Rows[0].Cells.Clear();
GridView1.Rows[0].Cells.Add(new TableCell());
GridView1.Rows[0].Cells[0].ColumnSpan = columncount;
GridView1.Rows[0].Cells[0].Text = "No Records Found";
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex; //this open new index that is edit mode
userDetails();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int userid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["UserId"].ToString()); //finding Datakeynames from gridview
string username = GridView1.DataKeys[e.RowIndex].Values["UserName"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand("Crudoperation", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@userid", userid);
cmd.Parameters.AddWithValue("@status", "delete");
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
userDetails();
Response.Write("<script language=javascript>alert('" + username + "'+'details deleted successfully');</script>");
}
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1; //after cancel button want go to one index back that's y -1
userDetails();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("AddNew"))
{
TextBox txtUsrname = (TextBox)GridView1.FooterRow.FindControl("txtftrusrname");
TextBox txtpwd = (TextBox)GridView1.FooterRow.FindControl("txtftrpassword"); //find textbox control on footer with crrosponding id
TextBox txtadress = (TextBox)GridView1.FooterRow.FindControl("txtftrAddress");
con.Open();
SqlCommand cmd = new SqlCommand("Crudoperation", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@username", txtUsrname.Text);
cmd.Parameters.AddWithValue("@password", txtpwd.Text);
cmd.Parameters.AddWithValue("@address", txtadress.Text);
cmd.Parameters.AddWithValue("@status","insert");
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
userDetails();
Response.Write("<script language=javascript>alert('" + txtUsrname.Text + "'+'Details inserted successfully');</script>");
}
else
{
Response.Write("<script language=javascript>alert('" + txtUsrname.Text + "'+' Details not inserted');</script>");
}
}
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int userid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
string username = GridView1.DataKeys[e.RowIndex].Values["UserName"].ToString();
TextBox txtpassword = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtpassword");
TextBox txtAddress = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtAddress");
con.Open();
SqlCommand cmd = new SqlCommand("Crudoperation", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@password", txtpassword.Text);
cmd.Parameters.AddWithValue("@address", txtpassword.Text);
cmd.Parameters.AddWithValue("@userid", userid);
cmd.Parameters.AddWithValue("@status", "update");
cmd.ExecuteNonQuery();
con.Close();
Response.Write("<script language=javascript>alert('" + username + "'+' Details Updated successfully!');</script>");
GridView1.EditIndex = -1;
userDetails();
}
}
Now run code and perform gridview operation using storeprocedure
Page Load:
userDetails Method:
GridView Events:
Database Operations:
User Interaction:
Above code demonstrates how to create a basic CRUD functionality using ASP.NET Web Forms and interact with a SQL Server database using stored procedures.