As I have written before about how to bind data with GridView Control with database.
Now, I in this article I will use Itemtemplate and Edittemplate where we will do Edit, Update and Delete the records.
Before to do it first of all create a database.
Run the following script in your Sql Server 2005.
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id =OBJECT_ID(N‘[dbo].[tbuser]‘) AND type in (N‘U’))
CREATE TABLE [dbo].[tbuser](
[id] [int] IDENTITY(1,1) NOT NULL,
[uid] [varchar](50) NOT NULL,
[Name] [varchar](50) NULL,
[address] [varchar](50) NULL,
CONSTRAINT [PK_tbuser] PRIMARY KEY CLUSTERED
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)ON [PRIMARY]
Well place the GridView control on a form and set the following property.
1.AutoGenerateColumns=”False”
And set the Gridview Events name is
onpageindexchanging=”GridView1_PageIndexChanging”
onrowcancelingedit=”GridView1_RowCancelingEdit”
onrowdeleting=”GridView1_RowDeleting”onrowediting=”GridView1_RowEditing”
onrowupdating=”GridView1_RowUpdating”
*Snapshot how to do set Events of GridView select the GridView and press f4
Or copy paste the following Source Code
<%@ Page Language=”C#” AutoEventWireup=”true”CodeFile=”user.aspx.cs” Inherits=”user” %>
<!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”>
<title>Untitled Page</title>
<form id=”form1″ runat=”server”>
<asp:TextBox ID=”Txt_uid” runat=”server”></asp:TextBox>
<asp:TextBox ID=”Txt_Name” runat=”server”></asp:TextBox>
<asp:TextBox ID=”Txt_Address” runat=”server” Height=”22px” >
<asp:TextBox ID=”Txt_Salary” runat=”server”></asp:TextBox>
<asp:Button ID=”Button1″ runat=”server” Height=”26px”onclick=”Button1_Click”
Text=”Insert” Width=”89px” />
<td class=”style2″ colspan=”2″>
<asp:GridView ID=”GridView1″ runat=”server”AutoGenerateColumns=”False”
CellPadding=”1″ ForeColor=”#333333″ GridLines=”None”
onpageindexchanging=”GridView1_PageIndexChanging”
onrowcancelingedit=”GridView1_RowCancelingEdit”
onrowdeleting=”GridView1_RowDeleting”onrowediting=”GridView1_RowEditing”
onrowupdating=”GridView1_RowUpdating” CellSpacing=”1″>
<RowStyle BackColor=”#EFF3FB” />
<asp:TemplateField HeaderText=”S.No”>
<%#Container.DataItemIndex +1 %>
<asp:Label ID=”Label5″ runat=”server”></asp:Label>
<asp:TemplateField HeaderText=”Uid”>
<asp:Label ID=”Label1″ runat=”server” Text=’<%# Eval(“uid”) %>‘></asp:Label>
<asp:Label ID=”lb_id” runat=”server” Text=’<%# Eval(“id”) %>‘></asp:Label>
<asp:Label ID=”lbl_edit” runat=”server” Text=’<%# Eval(“id”) %>‘></asp:Label>
<asp:TemplateField HeaderText=”Name”>
<asp:Label ID=”Label2″ runat=”server” Text=’<%# Eval(“Name”) %>‘></asp:Label>
<asp:TextBox ID=”txt_ename” runat=”server” Text=’<%# Eval(“name”)%>‘></asp:TextBox>
<asp:TemplateField HeaderText=”Salary”>
<asp:Label ID=”Label3″ runat=”server” Text=’<%# Eval(“Salary”) %>‘></asp:Label>
<asp:TextBox ID=”txt_esal” runat=”server” Text=’<%# Eval(“Salary”)%>‘></asp:TextBox>
<asp:TemplateField HeaderText=”Address”>
<asp:Label ID=”Label4″ runat=”server” Text=’<%# Eval(“Address”) %>‘></asp:Label>
<asp:TextBox ID=”txt_eadd” runat=”server” Height=”81px”
Text=’<%# Eval(“address”) %>‘
TextMode=”MultiLine” Width=”246px”></asp:TextBox>
<asp:TemplateField HeaderText=”Edit”>
<asp:LinkButton ID=”LinkButton1″ runat=”server”CommandName=”edit”>Edit</asp:LinkButton>
<asp:LinkButton ID=”LinkButton2″ runat=”server”CommandName=”update”>Update</asp:LinkButton>
<asp:LinkButton ID=”LinkButton3″ runat=”server”CommandName=”cancel”>Cancel</asp:LinkButton>
<asp:TemplateField HeaderText=”Delete”>
<asp:LinkButton ID=”LinkButton4″ runat=”server” CommandName=”delete”
onclientclick=”return confirm(‘Are you sure want to delete the current record ?’)”>Delete</asp:LinkButton>
<FooterStyle BackColor=”#507CD1″ Font-Bold=”True” ForeColor=”White”/>
<PagerStyle BackColor=”#2461BF” ForeColor=”White”HorizontalAlign=”Center” />
<SelectedRowStyle BackColor=”#D1DDF1″ Font-Bold=”True”ForeColor=”#333333″ />
<HeaderStyle BackColor=”#507CD1″ Font-Bold=”True” ForeColor=”White”/>
<EditRowStyle BackColor=”#FF9999″ />
<AlternatingRowStyle BackColor=”White” />
using System.Collections;
using System.Configuration;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient; // add the namespace
public partial class user : System.Web.UI.Page
SqlConnection con = new SqlConnection(); // for connection
protected void Page_Load(object sender, EventArgs e)
con.ConnectionString =ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;//accessing connection name from Web.config
if (con.State == ConnectionState.Closed)
grdview(); // calling the grdview function
if (con.State == ConnectionState.Closed)
adp = new SqlDataAdapter(“select * from tbuser order by id desc”, con); //fetching the records from table
Response.Write(“No record found”);
GridView1.DataSource = dt;
protected void Button1_Click(object sender, EventArgs e)
if (con.State == ConnectionState.Closed)
adp = new SqlDataAdapter(“Select uid from tbuser where uid=@uid”, con); // will check the uid if exists then display else condition
adp.SelectCommand.Parameters.AddWithValue(“@uid”, Txt_uid.Text);
// will insert the unique record of uid
cmd = new SqlCommand(“insert into tbuser values(@uid,@Name,@Address,@Salary)”, con);
cmd.Parameters.AddWithValue(“@uid”, Txt_uid.Text);
cmd.Parameters.AddWithValue(“@Name”, Txt_Name.Text);
cmd.Parameters.AddWithValue(“@Address”, Txt_Address.Text);
cmd.Parameters.AddWithValue(“@Salary”, Txt_Salary.Text);
Response.Write(“user name is already exits”);
protected void GridView1_PageIndexChanging(object sender,GridViewPageEventArgs e)
GridView1.PageIndex = e.NewPageIndex; // for pageindexing
protected void GridView1_RowCancelingEdit(object sender,GridViewCancelEditEventArgs e)
GridView1.EditIndex = -1; // will cancel the updating
protected void GridView1_RowDeleting(object sender,GridViewDeleteEventArgs e)
{ //will delete the Record
Label id = ((Label)(GridView1.Rows[e.RowIndex].FindControl(“lb_id”))); // here we will find the label name “lb_id” which is bound with
if (con.State == ConnectionState.Closed)
cmd = new SqlCommand(“delete from tbuser where id=@id”, con);
cmd.Parameters.AddWithValue(“@id”, id.Text);
protected void GridView1_RowEditing(object sender,GridViewEditEventArgs e)
GridView1.EditIndex = e.NewEditIndex;
protected void GridView1_RowUpdating(object sender,GridViewUpdateEventArgs e)
// The label which is in Edittemplate name “lbl_edit” bind with id field from the table
Label id = ((Label)(GridView1.Rows[e.RowIndex].FindControl(“lbl_edit”))) ;
if (con.State == ConnectionState.Closed)
//In edittemplate where we placed the textbox which were bind with the fields and here we will find the
// controls and will access the fields and update the records
cmd = new SqlCommand(“update tbuser set name=@name,salary=@salary,address=@address where id=@id”, con);
cmd.Parameters.AddWithValue(“@name”, ((TextBox)(GridView1.Rows[e.RowIndex].FindControl(“txt_ename”))).Text);//name
cmd.Parameters.AddWithValue(“@salary”, Convert.ToInt32(((TextBox)(GridView1.Rows[e.RowIndex].FindControl(“txt_esal”))).Text));//salary
cmd.Parameters.AddWithValue(“@address”, ((TextBox)(GridView1.Rows[e.RowIndex].FindControl(“txt_eadd”))).Text);//address
cmd.Parameters.AddWithValue(“@id”, id.Text);//id
GridView1.EditIndex = -1;
Select the GridView and click on the Columns and add the TemplateField.
Following the image will show the Edit Templates option click on it and it will open the Itemtemplate and Edit template fields.
Following image after click on the Edit Templates
Select the Edit Linkbutton and set the CommandName =”edit” and for Update is “update”, Cancel=”cancel” and for Delete =”delete”
Inserting the records and displaying the user name is already exists…
Editing the records after click the EDIT button and it will open the Edittemplate where we place the Textbox controls
Here the data will delete after confirmation of the record when we click on DELETE button.