Edit ,Insert,Delete,Update in Gridview in C# ASP.NET

in this article , i will show to add , delete , update and cancle in the gridview , i have used textbox to edit the values 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="test" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
<style type="text/css">
.Gridview
{
font-family:Verdana;
font-size:10pt;
font-weight:normal;
color:black;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>

<asp:GridView ID="gvDetails" DataKeyNames="Id,Name" runat="server"
AutoGenerateColumns="False" CssClass="Gridview" HeaderStyle-BackColor="#61A6F8"
ShowFooter="True" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White"
onrowcancelingedit="gvDetails_RowCancelingEdit"
onrowdeleting="gvDetails_RowDeleting" onrowediting="gvDetails_RowEditing"
onrowupdating="gvDetails_RowUpdating"
onrowcommand="gvDetails_RowCommand"
        >
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:ImageButton ID="imgbtnUpdate" CommandName="Update" runat="server" ImageUrl="~/image/imgres.jpg" ToolTip="Update" Height="20px" Width="20px" />
<asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel" ImageUrl="~/image/cancel.jpg" ToolTip="Cancel" Height="20px" Width="20px" />
</EditItemTemplate>
<ItemTemplate>
<asp:ImageButton ID="imgbtnEdit" CommandName="Edit" runat="server" ImageUrl="~/image/edit.jpg" ToolTip="Edit" Height="20px" Width="20px" />
<asp:ImageButton ID="imgbtnDelete" CommandName="Delete" Text="Edit" runat="server" ImageUrl="~/image/-.jpg" ToolTip="Delete" Height="20px" Width="20px" />
</ItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="imgbtnAdd" runat="server" ImageUrl="~/image/insert.png" CommandName="AddNew" Width="30px" Height="30px" ToolTip="Add new User" ValidationGroup="validaiton" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<EditItemTemplate>
<asp:Label ID="lbleditname" runat="server" Text='<%#Eval("name") %>'/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblname" runat="server" Text='<%#Eval("Name") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtaftername" runat="server"/>
<asp:RequiredFieldValidator ID="rfvname" runat="server" ControlToValidate="txtaftername" Text="*" ValidationGroup="validaiton"/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Phone">
<EditItemTemplate>
<asp:TextBox ID="txtphone" runat="server" Text='<%#Eval("Phone") %>'/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblphone" runat="server" Text='<%#Eval("Phone") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtafterphone" runat="server"/>
<asp:RequiredFieldValidator ID="rfvphone" runat="server" ControlToValidate="txtafterphone" Text="*" ValidationGroup="validaiton"/>
<asp:RegularExpressionValidator ID="REVphone" runat="server"
                        ControlToValidate="txtafterphone" ErrorMessage="**" SetFocusOnError="True"
                        ValidationExpression="^[789]\d{9}$"></asp:RegularExpressionValidator>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email">
<EditItemTemplate>
<asp:TextBox ID="txtemail" runat="server" Text='<%#Eval("Email") %>'/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblemail" runat="server" Text='<%#Eval("Email") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtafteremail" runat="server"/>
<asp:RequiredFieldValidator ID="rfvemail" runat="server" ControlToValidate="txtafteremail" Text="*" ValidationGroup="validaiton"/>

                    <asp:RegularExpressionValidator ID="REVemail" runat="server"
                        ControlToValidate="txtafteremail" ErrorMessage="**" SetFocusOnError="True"
                        ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
</FooterTemplate>
</asp:TemplateField>
</Columns>

<HeaderStyle BackColor="#61A6F8" Font-Bold="True" ForeColor="White"></HeaderStyle>
</asp:GridView>
</div>
<div>
<asp:Label ID="lblresult" runat="server"></asp:Label>
</div>
</form>
</body>
</html>




Design:-

C# code:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Drawing;

public partial class test : System.Web.UI.Page
{
   
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conString"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindEmployeeDetails();
            lblresult.Text = "";
        }
    }
    protected void BindEmployeeDetails()
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("Select * from reg", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        con.Close();
        if (ds.Tables[0].Rows.Count > 0)
        {
            gvDetails.DataSource = ds;
            gvDetails.DataBind();
        }
        else
        {
            ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
            gvDetails.DataSource = ds;
            gvDetails.DataBind();
            int columncount = gvDetails.Rows[0].Cells.Count;
            gvDetails.Rows[0].Cells.Clear();
            gvDetails.Rows[0].Cells.Add(new TableCell());
            gvDetails.Rows[0].Cells[0].ColumnSpan = columncount;
            gvDetails.Rows[0].Cells[0].Text = "No Records Found";
        }
    }
    protected void gvDetails_RowEditing(object sender, GridViewEditEventArgs e)
    {
        gvDetails.EditIndex = e.NewEditIndex;
        BindEmployeeDetails();
    }
    protected void gvDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        int userid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Value.ToString());
        string username = gvDetails.DataKeys[e.RowIndex].Values["Name"].ToString();
        TextBox txtphone= (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtphone");
        TextBox txtemail= (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtemail");
        con.Open();
        SqlCommand cmd = new SqlCommand("update reg set Phone ='"txtphone.Text + "',Email ='"txtemail.Text + "' where Id=" + userid, con);
        cmd.ExecuteNonQuery();
        con.Close();
        lblresult.ForeColor = Color.Green;
        lblresult.Text = username + " Details Updated successfully";
        gvDetails.EditIndex = -1;
        BindEmployeeDetails();
    }
    protected void gvDetails_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        gvDetails.EditIndex = -1;
        BindEmployeeDetails();
    }
    protected void gvDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int userid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Values["Id"].ToString());
        string username = gvDetails.DataKeys[e.RowIndex].Values["Name"].ToString();
        con.Open();
        SqlCommand cmd = new SqlCommand("delete from reg where Id=" + userid, con);
        int result = cmd.ExecuteNonQuery();
        con.Close();
        if (result == 1)
        {
            BindEmployeeDetails();
            lblresult.ForeColor = Color.Red;
            lblresult.Text = username + " details deleted successfully";
        }
    }
    protected void gvDetails_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("AddNew"))
        {
            TextBox txtname = (TextBox)gvDetails.FooterRow.FindControl("txtaftername");
            TextBox txtphone = (TextBox)gvDetails.FooterRow.FindControl("txtafterphone");
            TextBox txtemail = (TextBox)gvDetails.FooterRow.FindControl("txtafteremail");
            con.Open();
            SqlCommand cmd =
            new SqlCommand(
            "insert into reg (Name,Phone,email) values('" + txtname.Text + "','" +
            txtphone.Text + "','" + txtemail.Text + "')", con);
            int result = cmd.ExecuteNonQuery();
            con.Close();
            if (result == 1)
            {
                BindEmployeeDetails();
                lblresult.ForeColor = Color.Green;
                lblresult.Text = txtname.Text + " Details inserted successfully";
            }
            else
            {
                lblresult.ForeColor = Color.Red;
                lblresult.Text = txtname.Text + " Details not inserted";
            }
        }
    }
}







Edit ,Insert,Delete,Update in Gridview in C# ASP.NET Edit ,Insert,Delete,Update in Gridview in C# ASP.NET Reviewed by NEERAJ SRIVASTAVA on 11:05:00 PM Rating: 5

1 comment:

  1. int userid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Values["Id"].ToString());
    plz explain what is DataKeys works in tis line

    ReplyDelete

Powered by Blogger.