In this post i will explain you GridView CRUD: Select Insert Edit Update Delete using Single Stored procedure with Alert Confirmations on Delete from GridView.

I have a gridview I want perform insert ,update ,delete,edit operation along with that i also want to delete the record from gridview  by click on delete button with a alert message “Are you sure want to delete?”
To achieve all  these functionalities i have used gridview event.

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 a created storeprocedure for performing insert ,update,delete,edit. I have declared a @status parameter and accordingly it we will perform database operation.
As we can see in the below query I have declared nullabe parameter in the store procedure .ie optional parameter. If don’t about the store 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
1.Now open visual studio and add empty website.
2.Now add a gridview to the page

3.Right click on gridview and then  click on gridview property ,double click on the following event of gridview.
i have explain some gridview view event which are very useful.
1) Onrowcancelingedit
The RowCancelingEdit event is occur when the Cancel button of a row in edit mode is clicked2) Onrowediting
The RowEditing event is fire when a row’s Edit button is clicked, but before the GridView control enters edit mode.
3) Onrowupdating
The RowUpdating event is fire when a row’s Update button is clicked, but before the GridView control updates the row
5) Onrowdeleting
The RowDeleting event is fire when a row’s Delete button is clicked, but before the GridView control deletes the row.
6)OnRowCommand
The RowCommand event is fire when a button is clicked in the GridView control.

 <%@ 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

 Use of Multiple DataKeyNames (DataKeys) in ASP.Net GridView, How to find datakey value of gridview

DataKeyNames property allows us to set the names of the Column Fields in a gridview that
you want to use in your code but you do not want to display it for Example Primary Keys,ID,Username.

In my example i don’t want to display userid but i want to use it in code behind for deleting and updating record.

IsPostBack is a property of the Asp.Net page that checks whether the page is loaded first time or it is loaded due to button on page.
Now i have written code for operation on the event of 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

The post Insert, Update, Delete in Gridview using Single Stored Procedure appeared first on Software Development | Programming Tutorials.



Read More Articles