This example shows how to edit and update records in a GridView in ASP.NET. This example is helpful in situations where an administrator needs to edit several records from the database. For demonstration, I have created a database (named Database.mdf) in which we have a table named tbl_Employee.
Table Schema used in this example
CREATE TABLE [dbo].[tbl_Employee] (
[ID] INT NOT NULL,
[Name] VARCHAR (50) NULL,
[City] VARCHAR (50) NULL,
PRIMARY KEY CLUSTERED ([ID] ASC)
);
Let's Begin
- Drop a GridView Control from the toolbox and set AutoGenerateColumns to false.
- Add the Columns Collection (tag) that manages the collection of column fields.
- Add TemplateField inside the Columns Collection that is used to display custom content in a data-bound control.
- Add an ItemTemplate in the TemplateField that specifies the content to display for the items in a TemplateField.
- Add an EditItemTemplate in the TemplateField that specifies a custom user interface (UI) for the item in edit mode.
- Set the Command name property to Edit in the Edit button, Update in the Update button and Cancel in the Cancel Button depending on their respective Events.
- Add OnRowEditing, OnRowUpdating and OnRowCancelingEdit events to the GridView.
Default.aspx Code:
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="6" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btn_Edit" runat="server" Text="Edit" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="btn_Update" runat="server" Text="Update" CommandName="Update"/>
<asp:Button ID="btn_Cancel" runat="server" Text="Cancel" CommandName="Cancel"/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lbl_ID" runat="server" Text='<%#Eval("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lbl_Name" runat="server" Text='<%#Eval("Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_Name" runat="server" Text='<%#Eval("Name") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<ItemTemplate>
<asp:Label ID="lbl_City" runat="server" Text='<%#Eval("City") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_City" runat="server" Text='<%#Eval("City") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="#663300" ForeColor="#ffffff"/>
<RowStyle BackColor="#e7ceb6"/>
</asp:GridView>
</div>
</form>
Default.aspx.cs Code
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
//Connection String from web.config File
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con;
SqlDataAdapter adapt;
DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
ShowData();
}
}
//ShowData method for Displaying Data in Gridview
protected void ShowData()
{
dt = new DataTable();
con = new SqlConnection(cs);
con.Open();
adapt = new SqlDataAdapter("Select ID,Name,City from tbl_Employee",con);
adapt.Fill(dt);
if(dt.Rows.Count>0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
con.Close();
}
protected void GridView1_RowEditing(object sender, System.Web.UI.WebControls.GridViewEditEventArgs e)
{
//NewEditIndex property used to determine the index of the row being edited.
GridView1.EditIndex = e.NewEditIndex;
ShowData();
}
protected void GridView1_RowUpdating(object sender, System.Web.UI.WebControls.GridViewUpdateEventArgs e)
{
//Finding the controls from Gridview for the row which is going to update
Label id=GridView1.Rows[e.RowIndex].FindControl("lbl_ID") as Label;
TextBox name = GridView1.Rows[e.RowIndex].FindControl("txt_Name") as TextBox;
TextBox city = GridView1.Rows[e.RowIndex].FindControl("txt_City") as TextBox;
con = new SqlConnection(cs);
con.Open();
//updating the record
SqlCommand cmd = new SqlCommand("Update tbl_Employee set Name='"+name.Text+"',City='"+city.Text+"' where ID="+Convert.ToInt32(id.Text),con);
cmd.ExecuteNonQuery();
con.Close();
//Setting the EditIndex property to -1 to cancel the Edit mode in Gridview
GridView1.EditIndex = -1;
//Call ShowData method for displaying updated data
ShowData();
}
protected void GridView1_RowCancelingEdit(object sender, System.Web.UI.WebControls.GridViewCancelEditEventArgs e)
{
//Setting the EditIndex property to -1 to cancel the Edit mode in Gridview
GridView1.EditIndex = -1;
ShowData();
}
}
Final Preview:

I hope you like it. Thanks.

usukhuuPosted Dec 10, 2024, 3:27 AM
Good mey ajj
P SalazarPosted May 2, 2024, 12:48 PM
What is the accion that fires the edit mode in the grid? CommandName="Edit" ??
raj rahulPosted Oct 1, 2021, 12:13 PM
Hey.Is it possible if i just use 1 edit button for all the rows and when the update button is clicked the active row can be edited?
Vianney KirumiraPosted Jan 26, 2021, 7:14 PM
Hey, i want to be able to do the following: click edit botton-> new form open with row data in it's text field, then i do editing and update/save. please help me with such code
shallu palPosted Aug 6, 2020, 4:00 AM
I am getting an error say "Object reference not set to an instance of an object." in line "DropDownList1.DataSource = dt;". Please reply with a solution.
Yashwanth YashasPosted Feb 28, 2020, 1:53 AM
There is no validation in that above example,,, i need validation before updating the username and other textboxes..
Neeta LokhandePosted Sep 13, 2019, 7:30 AM
My values are not getting update after pressing update button. I retrieve data via response.write. It shows me old data. My code snippet is:- Label id = GridView1.Rows[e.RowIndex].FindControl("lbl_ID") as Label; TextBox name = GridView1.Rows[e.RowIndex].FindControl("txt_name") as TextBox; TextBox city = GridView1.Rows[e.RowIndex].FindControl("txt_City") as TextBox; Response.Write(name.Text); Response.Write(city.Text); Pls. tell mewhat to do to get new updated values.
Bheem RaoPosted Jun 17, 2019, 12:29 AM
Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation. I have set EnableEventValidation="false" for the page but textbox in the gridview is not converting as textbox hence could able to modify. Please help me out in this regards.
Jerald Jayaraj DPosted Jun 15, 2019, 6:45 AM
Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation. im running in vs2010 and ms access i am facing this probelm kindly help me out
Marcus LimaPosted Jun 6, 2019, 3:04 PM
Hey Anoop, nice post, very useful! When in Edit mode, can I change the field to a DropDownList ? I need to limit input options for users.
sunil cPosted Sep 15, 2018, 9:44 AM
Or else.. I have planned for two gridviews.. How to update both with a single button?
sunil cPosted Sep 15, 2018, 9:43 AM
Hi... Is it possible to have one row of gridview in two lines??
Ali AbbasiPosted Sep 6, 2018, 12:26 AM
Anoop sir.. kindly tell me about " DataTable dt; "...
Manjay KumarPosted Sep 1, 2018, 3:23 AM
Its very useful
Sivakumar ChallaPosted Jun 18, 2018, 8:31 AM
I need to give the name buttons column in the gridview
Sivakumar ChallaPosted Jun 18, 2018, 8:07 AM
Can i give a name (events) to edit,update button column in gridview
sanjay sbPosted Mar 9, 2018, 3:21 AM
Thank you very much bro..
Isaac HatilimaPosted Feb 24, 2018, 3:08 AM
Hey, I have done as you said but my data won't change when I update. It maintains the same value.
Dhimesh ParmarPosted Feb 22, 2018, 6:57 AM
How To Use with RadioButton(MALE /FEMALE)
Umesh BharadPosted Dec 19, 2017, 6:23 AM
Give me source code
Umesh BharadPosted Dec 19, 2017, 6:22 AM
Hello i want to change button text after click on button ex. when i click on edit button and it replace name edit as a update not use grid view normal button and then i update user profile
Jalpa FalduPosted Aug 17, 2017, 7:36 AM
Good Demo project...
Pratik ShirsePosted Jul 27, 2017, 4:16 PM
Good one.... can you help how to calculation in row between Rate * Qty =Total
SRIHARI VENKATESANPosted Apr 13, 2017, 12:11 AM
It will just update in the webpage only it doesn't affect database values could you please provide solution to update database also..
Amarkant SemwalPosted Dec 29, 2016, 3:16 AM
Protected void GrdV1_RowEditing(object sender, GridViewEditEventArgs e) { GrdV1.EditIndex = e.NewEditIndex; Display(); } protected void GrdV1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { GrdV1.EditIndex = -1; Display(); } protected void GrdV1_RowDeleting(object sender, GridViewDeleteEventArgs e) { string Sno = GrdV1.DataKeys[e.RowIndex].Value.ToString(); string str2 = "Delete from Userinfo where CardId='" + Sno + "'"; DataTable dg = cl.databyQ(str2); Display(); Response.Write("<script>alert('Record Delete Successfully')</script>"); } protected void GrdV1_RowUpdating(object sender, GridViewUpdateEventArgs e) { Label id = GrdV1.Rows[e.RowIndex].FindControl("lbl_ID") as Label; TextBox name = GrdV1.Rows[e.RowIndex].FindControl("txt_Name") as TextBox; string sql = "update Userinfo set UName='" + name + "' where CardId='"+id+"'"; DataTable ds = cl.databyQ(sql); GrdV1.EditIndex = -1; Display(); }
Amarkant SemwalPosted Dec 29, 2016, 3:15 AM
Update opration are not work sir help me
Manav PandyaPosted Sep 19, 2016, 6:04 AM
Nice one bro ...
Dave GreenPosted Sep 9, 2016, 4:50 AM
Superb article thank you ! The 'Final Preview' is a great idea so we can see what we're aiming for :-)
jak malPosted Jun 24, 2016, 5:21 AM
String str = System.Configuration.ConfigurationManager.ConnectionStrings["WebConnectionString"].ToString(); cn = new MySqlConnection(str); cn.Open(); TextBox id = GridView1.Rows[e.RowIndex].FindControl("TextBox1") as TextBox; TextBox problem = GridView1.Rows[e.RowIndex].FindControl("TextBox3") as TextBox; TextBox closeTime = GridView1.Rows[e.RowIndex].FindControl("TextBox5") as TextBox; TextBox st = GridView1.Rows[e.RowIndex].FindControl("TextBox6") as TextBox; string cl = "UPDATE cms.complain_master SET ProbDetails='"+problem.Text+"',EndDate='"+closeTime.Text+"',Status='Close' where CPID='"+id.Text+"'"; cmdCloser = new MySqlCommand(cl,cn); cmdCloser.ExecuteNonQuery(); cn.Close();
jak malPosted Jun 24, 2016, 5:18 AM
I can update values on webpage only and after selection of update button it will store old values only in database. It can't find new values which i have changed. Please help me...
Ankit SharmaPosted May 22, 2016, 4:43 PM
protected void GridView1_RowUpdating(object sender, System.Web.UI.WebControls.GridViewUpdateEventArgs e) { //Finding the controls from Gridview for the row which is going to update Label Name = GridView1.Rows[e.RowIndex].FindControl("e_name") as Label; Label EmpID = GridView1.Rows[e.RowIndex].FindControl("e_id") as Label; Label RqID = GridView1.Rows[e.RowIndex].FindControl("r_id") as Label; TextBox reqstip = GridView1.Rows[e.RowIndex].FindControl("r_ip") as TextBox; con.Open(); //updating the record MySqlCommand cmd = new MySqlCommand("Update req SET r_ip = '" + reqstip.Text + "' WHERE r_id=" +RqID.Text, con); cmd.ExecuteNonQuery();
Ankit SharmaPosted May 22, 2016, 4:43 PM
this is the full code of the update event.. please help me in this
Ankit SharmaPosted May 22, 2016, 4:41 PM
I'm trying this code on my project but it is saying that Object reference not set to an instance of an object. can u please help me in this??
Ankit SharmaPosted May 22, 2016, 4:40 PM
MySqlCommand cmd = new MySqlCommand("Update req SET r_ip = '" + reqstip.Text + "' WHERE r_id=" +RqID.Text, con);
stelle thomasPosted Mar 7, 2016, 8:07 AM
Thank you so much for such a simple explanation. But if I want to delete and add new data in database then what changes should I do in my code??. Please answer my question as soon as possible. I really want to know . It will be very beneficial for my project.