Home | Tutorial | Articles | Forum | Interview Question |... Poll | Web Links | Certification | Search

How to Edit,Update,Delete in Gridview - C#, ASP.Net, VB.Net
http://www.dotnetspark.com/kb/643-how-to-editupdatedelete-gridvi...
Home | Tutorial | Articles | Forum | Interview Question | Code Snippets | News | Fun Zone |
Poll | Web Links | Certification | Search
Welcome :Guest
Ads by Google
Data Gridview
ASP Net C#
Gridview WPF
Gridview Bind
Home >> Articles >>
ASP.NET >>
Post New
Resource
How to Edit,Update,Delete in Gridview
Posted By :Syed Shakeer Hussain
Posted Date :16/06/2009
Category: ASP.NET URL: http://www.dotnetspark.com
Sign In
Register
Win Surprise
Gifts!!!
Congratulations!!!
Subscribe to
Articles
Points :25
Maps For .NET Websites
Customizable Interactive Flash Maps For
Your Website. Starting at $149!
www.FlashMaps.com
SFTP components for .NET
The fastest and the most powerful SFTP for
VB.NET, C#, ASP.NET
www.eldos.com/SecureBlackbox
13214 IT Jobs Found
Better Roles, Better Salaries Naukri.com Post Your Resume Now!
Naukri.com
Free .NET Distrib Cache
Scale .NET Apps. Reduce db trips Download
Free copy (not a trial).
www.AlachiSoft.com/NCacheExpress
Top 5
Contributors of
the Month
Syed Shakeer
Hussain
Dhananjay Kumar
Update, Delete, Cancel in Gridview
In this Article you can learn how to edit, update, delete, and cancel in gridview.
First drag and drop Gridview.In gridview properties set AutoGenarateColumns to False.
Next open Default.aspx source code. To make a columns in Gridview use
<asp:TemplateField></asp:TemplateField>
Here first I created a table name 'emp' in my database.it contains 3 colomns as
id,name,marks,I am creating this colomns in gridview as follows:
Sunil Yadav
01
Vikramraj
laptop charles
1 of 21
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
Style="z-index: 100;left: 298px; position: absolute; top: 118px">
<Columns >
<asp:TemplateField HeaderText ="IDNO">
<ItemTemplate>
<asp:LabelID="lblid"runat="server"Text='<%#Eval("rowid")%>'></asp:Labe>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" >
<ItemTemplate > <%#Eval("name") %></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText ="Marks">
<ItemTemplate><%#Eval("marks") %></ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
7/7/2010 4:57 PM
How to Edit,Update,Delete in Gridview - C#, ASP.Net, VB.Net
http://www.dotnetspark.com/kb/643-how-to-editupdatedelete-gridvi...
In default.asp.cs page fill the gridview using SqlDataAdapter using below code:
1
2
3
4
5
6
SqlDataAdapter da = new SqlDataAdapter("select * from emp", conn);
DataSet ds = new DataSet();
da.Fill(ds, "emp");
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
conn.Close();
Next
in
Default.asp
page
select
your
gridview
in
AutoGenarateDeleteButton=True and AutoGenarateEditButton=True.
Properties
set
Next we have to write a code for editing,updating,cancel:In Default.aspx source code
we have to add <EditItemTemplate>
This <EditItemTemplate> is used to Edit the Row in Gridview.Here I am going to Edit only
two columns name and marks.
For Editing a Gridview:
In Gridview Events:Double Click on RowEditing Event and write below code
1
2
3
4
5
6
protected void GridView1_RowEditing(object sender,GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
bind();
}
When you click on Edit link it shows Update,Cancel links
For Updating a Gridview:
Updating link
Gridview.
is
used
to
update
a
Particular
row
in
emp
table
using
Double click on RowUpdating Event and write below code
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
2 of 21
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs
e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label lbl = (Label)row.FindControl("lblid");
TextBox textname = (TextBox)row.FindControl("textbox1");
TextBox textmarks = (TextBox)row.FindControl("textbox2");
GridView1.EditIndex = -1;
conn.Open();
SqlCommand cmd = new SqlCommand("update emp set marks=" +
textmarks.Text + " , name='" + textname.Text + "' where rowid=" + lbl.Text +
"", conn);
cmd.ExecuteNonQuery();
conn.Close();
bind();
}
7/7/2010 4:57 PM
How to Edit,Update,Delete in Gridview - C#, ASP.Net, VB.Net
http://www.dotnetspark.com/kb/643-how-to-editupdatedelete-gridvi...
For Canceling a gridview row Operation:
Cancel
Link in used to cancel the particular row operation before upadating.when you
click on Gricview it goes in first stage.
Double click on RowCancelingEdit Event and wrtie belwo code
1
2
3
4
5
protected void GridView1_RowCancelingEdit(object
sender,GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
bind();
}
For Deleting a Gridview row:
Delete Link is used to delete a Row in a emp table.it permanently deletes a
particular Row From GridView
Double Click on RowDeleting Event and write below code
01
02
03
04
05
06
07
08
09
10
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs
e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label lbldeleteID = (Label)row.FindControl("lblid");
conn.Open();
SqlCommand cmd = new SqlCommand("delete emp where rowid=" +
lbldeleteID.Text + "", conn);
cmd.ExecuteNonQuery();
conn.Close();
bind();
}
The Complete code is written as follows:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
3 of 21
<%@ Page Language="C#" AutoEventWireup="true"
Inherits="_Default" %>
CodeFile="Default.aspx.cs"
<!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 runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" Style="z-index: 100;
left: 298px; position: absolute; top: 118px" AllowSorting="True"
AutoGenerateDeleteButton="True" AutoGenerateEditButton="True"
OnRowEditing="GridView1_RowEditing"
OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowUpdating="GridView1_RowUpdating" OnRowDeleting="GridView1_RowDeleting"
BackColor="#FF8080" BorderColor="SaddleBrown" BorderStyle="None"
CellPadding="4" ForeColor="#333333" GridLines="None" PageSize="5">
<Columns >
<asp:TemplateField HeaderText ="IDNO"><ItemTemplate ><asp:Label
ID="lblid" runat ="server" Text ='<%#Eval("rowid") %>' ></asp:Label>
</ItemTemplate></asp:TemplateField>
<asp:TemplateField HeaderText="Name" ><ItemTemplate >
<%#Eval("name") %></ItemTemplate>
<EditItemTemplate >
<asp:TextBox ID="textbox1" runat ="server" Text
='<%#Eval("name") %>'></asp:TextBox>
7/7/2010 4:57 PM
How to Edit,Update,Delete in Gridview - C#, ASP.Net, VB.Net
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
http://www.dotnetspark.com/kb/643-how-to-editupdatedelete-gridvi...
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText ="Marks"><ItemTemplate>
<%#Eval("marks") %> </ItemTemplate>
<EditItemTemplate >
<asp:TextBox ID="textbox2" runat ="server" Text
='<%#Eval("marks") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#990000" Font-Bold="True"
ForeColor="White" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True"
ForeColor="Navy" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333"
HorizontalAlign="Center" />
<HeaderStyle BackColor="#990000" Font-Bold="True"
ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
</div>
</form>
</body>
</html><>
and in your .cs page
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
4 of 21
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection conn;
protected void Page_Load(object sender, EventArgs e)
{
conn = new SqlConnection("Data Source=INTHIYAAZ;Initial
Catalog=shakeer;uid=sa;pwd=sa;");
if(!IsPostBack )
{
bind();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs
e)
{
GridView1.EditIndex = e.NewEditIndex;
bind();
}
protected void GridView1_RowCancelingEdit(object sender,
GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
bind();
}
protected void GridView1_RowUpdating(object sender,
GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label lbl = (Label)row.FindControl("lblid");
TextBox textname = (TextBox)row.FindControl("textbox1");
TextBox textmarks = (TextBox)row.FindControl("textbox2");
7/7/2010 4:57 PM
How to Edit,Update,Delete in Gridview - C#, ASP.Net, VB.Net
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
5 of 21
http://www.dotnetspark.com/kb/643-how-to-editupdatedelete-gridvi...
GridView1.EditIndex = -1;
conn.Open();
SqlCommand cmd = new SqlCommand("update emp set marks=" +
textmarks.Text + " , name='" + textname.Text + "' where rowid=" + lbl.Text +
"", conn);
cmd.ExecuteNonQuery();
conn.Close();
bind();
}
public void bind()
{
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from emp", conn);
DataSet ds = new DataSet();
da.Fill(ds, "emp");
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
conn.Close();
}
protected void GridView1_SelectedIndexChanging(object sender,
GridViewSelectEventArgs e)
{
}
protected void GridView1_RowCommand(object sender,
GridViewCommandEventArgs e)
{
}
protected void GridView1_RowDeleting(object sender,
GridViewDeleteEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label lbldeleteID = (Label)row.FindControl("lblid");
conn.Open();
SqlCommand cmd = new SqlCommand("delete emp where rowid=" +
lbldeleteID.Text + "", conn);
cmd.ExecuteNonQuery();
conn.Close();
bind();
}
protected void GridView1_PageIndexChanging(object sender,
GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
bind();
}
}
7/7/2010 4:57 PM
How to Edit,Update,Delete in Gridview - C#, ASP.Net, VB.Net
http://www.dotnetspark.com/kb/643-how-to-editupdatedelete-gridvi...
Access Denied
(authentication_failed)
Your credentials could not
be authenticated:
"Credentials are missing.".
You will not be permitted
access until your
credentials can be verified.
This is typically caused by
an incorrect username
and/or password, but could
also be caused by network
Featured Articles
.NET Practices
Best
Best Practice
No 5:
No:
- Detecting
1:- Detecting
.NETHigh
application
Memorymemory
consuming
leaks
functions
Memory
leaks
in
.NET
in .NET
codeapplication
One of the have
important
always
factors
beingfor
programmer's
performancenightmare.
degradation
Memory
in .NET
leaksis
code
are
memory
biggestconsumption.
problems when
Many
it comes
developers
to production
just concentrate
servers. on
Productions
execution
servers
time
to determine
normally need
performance
to run with
bottle
least
necks
downintime.
a .NET
Memory
application.
leaks grow
Only slowly
and after sometime
measuring
executionthey
timebring
doesdown
not clearly
the server
give idea
by consuming
of where the
huge
performance
chunks of
memory.
issue
resides.
Maximum
Ok, said
time
and
people
done reboot
one of the
the system,
biggest task
makeisittowork
understand
temporarily
which
and
send a sorry
function,
assembly
note toorthe
class
customer
has consumed
for the downtime.
how much memory.
... Read More
In this tutorial we
will see how we can find which functions consume how much memory. This
article discusses
the best
practices involved
using
CLR
profiler for studying
Author:
Mohammad
Hussein
Company
URL:
http://www.dotnetspark.com
memory
allocation....
Read
More
Posted Date: 02/08/2009
Responses
Thank you Mr. Syed
This article was very useful to me.
Author: Syed Shakeer Hussain
http://www.dotnetspark.com
Posted Date: 03/08/2009
Company URL:
welcome Mr Hussein
Author: Mohammad Hussein
Posted Date: 09/08/2009
Company URL: http://www.dotnetspark.com
hi,
I'm having a problem with updating the data source from the GridView
I'm following what you did in the article, but in the GridView1_RowUpdating
handler when I execute update statement textname.Text for example gets me the
old values not the changed data in the TextBox.
Any idea what the problem is?
Is there an event that fires before the RowUpdating so it binds the old data again
with the TextBoxes in the Edit mode?
Thanks in advance.
Author: Syed Shakeer Hussain
http://www.dotnetspark.com
Posted Date: 11/08/2009
Company URL:
Hi,
for your porblem use
6 of 21
7/7/2010 4:57 PM
How to Edit,Update,Delete in Gridview - C#, ASP.Net, VB.Net
http://www.dotnetspark.com/kb/643-how-to-editupdatedelete-gridvi...
if(!IsPostBack )
{
bind();
}
you can see in my coding how i had used above code in my article.
and also understand what is the use of 'IsPostBack'
Author: deepa
Company URL:
Posted Date: 11/09/2009
hi,
this was very useful to me..
For me update is not working. i am getting oledbexception was unhandled by user
code
No value given for one or more required parameters.
This is my code.
for me GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
it shows null.All values are assigned to null. Can u pls help me?
protected void GridView1_RowUpdating(object sender,
System.Web.UI.WebControls.GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label lbl = (Label)row.FindControl("lblid");
//TextBox textID = (TextBox)row.FindControl("textbox1");
TextBox textfirstname = (TextBox)row.FindControl("textbox1");
TextBox textlastname = (TextBox)row.FindControl("textbox2");
TextBox textgender = (TextBox)row.FindControl("textbox3");
TextBox textdateofbirth = (TextBox)row.FindControl("textbox4");
TextBox textaddress= (TextBox)row.FindControl("textbox5");
TextBox textcityname = (TextBox)row.FindControl("textbox6");
GridView1.EditIndex = -1;
string conn = Convert.ToString(Application["con"]);
OleDbConnection myConnection = new OleDbConnection(conn);
myConnection.Open();
OleDbCommand cmd = new OleDbCommand("update EmployeeDetails set
firstname=" + textfirstname.Text + " , lastname=" + textlastname.Text + " where
ID=" + lbl.Text + "", myConnection);
cmd.ExecuteNonQuery();
myConnection.Close();
Employee_display();
}
Author: Syed Shakeer Hussain
http://www.dotnetspark.com
Posted Date: 11/09/2009
Company URL:
Hi Deepa,
In pageLoad event use !IsPostBack Property.
if(!IsPostBack )
{
bind();
7 of 21
7/7/2010 4:57 PM
How to Edit,Update,Delete in Gridview - C#, ASP.Net, VB.Net
http://www.dotnetspark.com/kb/643-how-to-editupdatedelete-gridvi...
}
you can see in my coding how i had used above code in my article.
and also understand what is the use of 'IsPostBack'
Author: deepa
Company URL:
Posted Date: 14/09/2009
Hi Hussain,
Thanks for your response. I have used IsPostBack Property.
I am new to programming. Can u please help me with this problem because
I am getting the same error?
I am sending the code:
namespace Employee_details
{
public partial class EmpRegDetails : System.Web.UI.Page
{
OleDbConnection myConnection;
protected void Page_Load(object sender, EventArgs e)
{
string conn = Convert.ToString(Application["con"]);
myConnection = new OleDbConnection(conn);
if (!IsPostBack)
{
bind();
}
}
public void bind()
{
myConnection.Open();
OleDbDataAdapter da = new OleDbDataAdapter("select * from EmployeeDetails",
myConnection);
Response.Write(da);
DataSet ds = new DataSet();
da.Fill(ds, "EmployeeDetails");
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
myConnection.Close();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
bind();
}
protected void GridView1_RowUpdating(object sender,
System.Web.UI.WebControls.GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label lbl = (Label)row.FindControl("lblid");
//TextBox textID = (TextBox)row.FindControl("textbox1");
8 of 21
7/7/2010 4:57 PM
How to Edit,Update,Delete in Gridview - C#, ASP.Net, VB.Net
TextBox
TextBox
TextBox
TextBox
TextBox
TextBox
http://www.dotnetspark.com/kb/643-how-to-editupdatedelete-gridvi...
textfirstname = (TextBox)row.FindControl("textbox1");
textlastname = (TextBox)row.FindControl("textbox2");
textgender = (TextBox)row.FindControl("textbox3");
textdateofbirth = (TextBox)row.FindControl("textbox4");
textaddress = (TextBox)row.FindControl("textbox5");
textcityname = (TextBox)row.FindControl("textbox6");
GridView1.EditIndex = -1;
string conn = Convert.ToString(Application["con"]);
OleDbConnection myConnection = new OleDbConnection(conn);
myConnection.Open();
OleDbCommand cmd = new OleDbCommand("update EmployeeDetails set
firstname=" + textfirstname.Text + " , lastname='" + textlastname.Text + "'
where RowID=" + lbl.Text + "", myConnection);
// SqlCommand cmd = new SqlCommand("update emp set marks=" +
textmarks.Text + " , name='" + textname.Text + "' where rowid=" + lbl.Text + "",
conn);
cmd.ExecuteNonQuery();
myConnection.Close();
bind();
// Response.Redirect("EmpRegform.aspx");
}
protected void GridView1_RowCancelingEdit(object sender,
System.Web.UI.WebControls.GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
bind();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs
e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label lbldeleteID = (Label)row.FindControl("lblid");
string conn = Convert.ToString(Application["con"]);
OleDbConnection myConnection = new OleDbConnection(conn);
myConnection.Open();
OleDbCommand cmd = new OleDbCommand("delete EmployeeDetails where
firstname=" + lbldeleteID.Text + "", myConnection);
cmd.ExecuteNonQuery();
myConnection.Close();
bind();
}
protected void GridView1_PageIndexChanging(object sender,
GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
bind();
9 of 21
7/7/2010 4:57 PM
How to Edit,Update,Delete in Gridview - C#, ASP.Net, VB.Net
http://www.dotnetspark.com/kb/643-how-to-editupdatedelete-gridvi...
}
}
}
Once again thanks,
Deepa
Author: Syed Shakeer Hussain
http://www.dotnetspark.com
Posted Date: 15/09/2009
Company URL:
Hi Deepa,Your code is correct.
But you had done a little mistake in OledbCommand.You didnot given a single
quote for textfirstname bcz it is a varchar datatype.you have to write as
firstname=''" + textfirstname.Text + "''
so use below command and try it in GridView1_RowUpdating:OleDbCommand cmd = new OleDbCommand("update EmployeeDetails set
firstname=''" + textfirstname.Text + "'' , lastname=''" + textlastname.Text + "''
where RowID=" + lbl.Text + "", myConnection);
Above Rowid is ''numeric'' data type so no nee to give single Quote.
And also in the same way in use belo code Gridview Row updating:OleDbCommand cmd = new OleDbCommand("delete EmployeeDetails where
Rowid=''" + lbldeleteID.Text + "''", myConnection);
After trying tell me if it helps you or not........
By the way where you from...
Author: deepa
Company URL:
Posted Date: 15/09/2009
Thanks Hussain. Its working now. I have done little mistake.
Thank you for ur time. ur article is very useful 2 me.
I am from Canada. I am working as a web designer. How abt u?
I saw u in dotnetspidr also.
regards,
deepa
Author: deepa
Company URL:
Posted Date: 15/09/2009
Hi Hussain,
One more thing please..
records are not deleting in the grid view. why?
10 of 21
7/7/2010 4:57 PM
How to Edit,Update,Delete in Gridview - C#, ASP.Net, VB.Net
http://www.dotnetspark.com/kb/643-how-to-editupdatedelete-gridvi...
code:
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label lbldeleteID = (Label)row.FindControl("lblid");
string conn = Convert.ToString(Application["con"]);
OleDbConnection myConnection = new OleDbConnection(conn);
myConnection.Open();
OleDbCommand cmd = new OleDbCommand("delete from EmployeeDetails where
firstname='" + lbldeleteID.Text + "'", myConnection);
cmd.ExecuteNonQuery();
myConnection.Close();
bind();
Could you please help? Thanks
Author: Syed Shakeer Hussain
http://www.dotnetspark.com
Posted Date: 16/09/2009
Company URL:
Hi deepa,
Again you done small mistake in Delete command.Just read the Error or execption
carefully.
You wrote
delete from EmployeeDetails where firstname='" + lbldeleteID.Text + "'
above you are deleting a empdetails through id,not with firstname.
Correct code is as follows:OleDbCommand cmd = new OleDbCommand("delete from EmployeeDetails where
RowID=" + lbldeleteID.Text + "",myConnection);
Author: sbmdude
Company URL:
Posted Date: 30/12/2009
How can I add Delete confirmation pop up message when I want to Delete a
record ?...
Author: Syed Shakeer Hussain
http://www.dotnetspark.com
Posted Date: 09/02/2010
Company URL:
Hi SW,
Sorry for giving late response..
for the first error:(Invalid column name 'ST01'.Problem ):-check the Enter Column
Name properly of given in a table.
For second Error:write private as Public
eg:public void bind()
{
string connstring = "Data Source=P-PC\\SQLEXPRESS;Initial Catalog=Peers;
Integrated Security=True";
cn = new SqlConnection(connstring);
11 of 21
7/7/2010 4:57 PM
How to Edit,Update,Delete in Gridview - C#, ASP.Net, VB.Net
http://www.dotnetspark.com/kb/643-how-to-editupdatedelete-gridvi...
cn.Open();
String str = "Select * from StudentNew";
SqlDataAdapter da = new SqlDataAdapter(str, cn);
DataSet ds = new DataSet();
da.Fill(ds, "StudentNew")
GridView1.DataSource = ds.Tables["StudentNew"];
GridView1.DataBind();
}
Author: Sameer
Company URL: http://www.dotnetspark.com
Posted Date: 12/04/2010
How to delete a row from datagridview in c# windows application using ms-access.
I want to delete the data through button event?
Author: gdswati
Company URL: http://www.dotnetspark.com
Posted Date: 21/05/2010
My delete is not working...It just doesnot fire the Rowdeleting event. I checked
my aspx as well but everything seems correct to me there...dont know what could
be the reason.
Can you please help me with this?
Thanks in advance.
Author: Syed Shakeer Hussain
http://www.dotnetspark.com
Posted Date: 21/05/2010
Company URL:
hi gdswati,
For Deleting a Gridview row:Delete Link is used to delete a Row in a emp table.it permanently deletes a
particular Row From GridView
Double Click on RowDeleting Event and write below code.
if also not work,send me the delete code what you had written.
Author: gdswati
Company URL: http://www.dotnetspark.com
Posted Date: 24/05/2010
Thanks a lott Syed Sakhir Hussain...I tried what you suggested...but that did not
work..the rowdeleting event is not raised...:-(
Here is my code...Please help me here...I tried putting breakpoint on the first line
of RowDeleting...but when I click on Delete link...It doesnot stop at the breakpoint
in Rowdeleting and the page is loaded as it is..
protected void grdItems_edit_RowDeleting(object sender,
GridViewDeleteEventArgs e)
{
GridViewRow row = (GridViewRow)grdItems_edit.Rows[e.RowIndex];
Label lbldeleteID = (Label)row.FindControl("lblid");
SqlConnection myConnection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("delete bod_items where rowid = '" +
lbldeleteID.Text + "'", myConnection);
12 of 21
7/7/2010 4:57 PM
How to Edit,Update,Delete in Gridview - C#, ASP.Net, VB.Net
http://www.dotnetspark.com/kb/643-how-to-editupdatedelete-gridvi...
try
{
myConnection.Open();
cmd.ExecuteNonQuery();
}
catch (Exception err)
{
lblResult.Text = "Error deleting record. ";
lblResult.Text += err.Message;
}
finally
{
myConnection.Close();
}
populateItems();
}
Author: gdswati
Company URL: http://www.dotnetspark.com
Posted Date: 24/05/2010
Here is my aspx as well..if you want to have a look at it.
<asp:GridView ID="grdItems_edit" runat="server" AllowSorting="True"
AutoGenerateColumns="False"
BackColor="White" BorderColor="Black" BorderStyle="Solid" BorderWidth="1px"
CellPadding="4" ForeColor="Black" GridLines="Vertical" width="670px"
OnRowCancelingEdit="grdItems_edit_RowCancelingEdit"
OnRowEditing="grdItems_edit_RowEditing"
OnRowUpdating="grdItems_edit_RowUpdating"
OnRowDeleting="grdItems_edit_RowDeleting" DataKeyNames="rowid"
OnRowUpdated="grdItems_edit_RowUpdated">
<Columns>
<asp:TemplateField HeaderText = "rowid">
<ItemTemplate>
<asp:Label ID = "lblid" runat = "server"> <%# Eval("rowid") %> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="invItemQty" HeaderText="QUANTITY"
SortExpression="invItemQty" >
<HeaderStyle Font-Size="Small" HorizontalAlign="Center" />
<ItemStyle Font-Names="Arial" Font-Size="Smaller" />
</asp:BoundField>
<asp:TemplateField SortExpression="invItemDesc" HeaderText="DESCRIPTION">
<ItemTemplate>
<asp:Label id="DESCRIPTION" runat="server"><%# Eval("invItemDesc")%>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDescription" runat="server" Text='<%#
Eval("invItemDesc") %>' TextMode="MultiLine"></asp:TextBox>
</EditItemTemplate>
<HeaderStyle Font-Size="Small" HorizontalAlign="Center" />
<ItemStyle Font-Names="Arial" Font-Size="Smaller" />
</asp:TemplateField>
<asp:BoundField DataField="invItemSerNum" HeaderText="SERIAL NUMBER"
SortExpression="invItemSerNum" >
<HeaderStyle Font-Size="Small" HorizontalAlign="Center" />
<ItemStyle Font-Names="Arial" Font-Size="Smaller" />
</asp:BoundField>
13 of 21
7/7/2010 4:57 PM
How to Edit,Update,Delete in Gridview - C#, ASP.Net, VB.Net
http://www.dotnetspark.com/kb/643-how-to-editupdatedelete-gridvi...
<asp:BoundField DataField="invItemAmt" HeaderText="AMOUNT"
SortExpression="invItemAmt" >
<HeaderStyle Font-Size="Small" HorizontalAlign="Center" />
<ItemStyle Font-Names="Arial" Font-Size="Smaller" />
</asp:BoundField>
<asp:CommandField ShowEditButton="True" ShowDeleteButton="True" >
<HeaderStyle Font-Size="Small" HorizontalAlign="Center" />
<ItemStyle Font-Names="Arial" Font-Size="Smaller" />
</asp:CommandField>
</Columns>
<FooterStyle BackColor="Black" ForeColor="Black" />
<PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White"
/>
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<EditRowStyle BorderColor="Black" BorderStyle="Solid" />
</asp:GridView>
Author: gdswati
Company URL: http://www.dotnetspark.com
Posted Date: 24/05/2010
I tried calling other function where I have query to delete row based on id of
selected row. But looks like my RowDeleting event is not fired when I click delete.
Author: Syed Shakeer Hussain
http://www.dotnetspark.com
Posted Date: 24/05/2010
Company URL:
Hi gdswati,
I think you did not write !isPostBack Property in PageLoad.
for eg:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Bind();
}
}
send your page LoadCode.....
waiting for you reply
Author: gdswati
Company URL: http://www.dotnetspark.com
Posted Date: 24/05/2010
I tried doing that...but then my gridview is populated twice.
Here is my pageload:
protected void Page_Load(object sender, EventArgs e)
{
string InvoiceNumber = "";
if (!this.IsPostBack)
{
if (Request.QueryString["InvoiceNumber"] != null)
{
InvoiceNumber = Request.QueryString["InvoiceNumber"].ToString();
ShowInfo();
}
14 of 21
7/7/2010 4:57 PM
How to Edit,Update,Delete in Gridview - C#, ASP.Net, VB.Net
http://www.dotnetspark.com/kb/643-how-to-editupdatedelete-gridvi...
}
//I tried adding the code you suggested here.
}
Author: gdswati
Company URL: http://www.dotnetspark.com
Posted Date: 24/05/2010
I tried doing that...but still same problem...my Rowdeleted is not fired
Here is my pageload:
protected void Page_Load(object sender, EventArgs e)
{
string InvoiceNumber = "";
if (!this.IsPostBack)
{
if (Request.QueryString["InvoiceNumber"] != null)
{
InvoiceNumber = Request.QueryString["InvoiceNumber"].ToString();
ShowInfo();
}
}
if (!IsPostBack)
populateItems();
}
Author: Syed Shakeer Hussain
http://www.dotnetspark.com
Posted Date: 24/05/2010
Company URL:
Hi gdswati,
Put the breakpoint in RowDelete Event.
run it breakpoint.if the breakpoint came in RowDelete Event then the problem is
in the ''Row Delete Event''.Or if the break point goes in the PageLoad without
going in the RowDelete Event then the problem with PostBak in Pageload.
in Page Load write the code as follows and run it:protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{ string InvoiceNumber = "";
if (Request.QueryString["InvoiceNumber"] != null)
{
InvoiceNumber = Request.QueryStrin["InvoiceNumber"].ToString();
ShowInfo();
populateItems();
}
}
wating for you reply
Author: gdswati
Company URL: http://www.dotnetspark.com
Posted Date: 24/05/2010
I did this...but when I click on delete...nothing happens...it doesnot even go to
any breakpoint...
15 of 21
7/7/2010 4:57 PM
How to Edit,Update,Delete in Gridview - C#, ASP.Net, VB.Net
http://www.dotnetspark.com/kb/643-how-to-editupdatedelete-gridvi...
Author: Syed Shakeer Hussain
http://www.dotnetspark.com
Posted Date: 24/05/2010
Company URL:
Hi,
I think the problem occuring due to the below selcetCommand in .aspx source
code.
<asp:CommandField ShowEditButton="True" ShowDeleteButton="True" >
<HeaderStyle Font-Size="Small" HorizontalAlign="Center" />
<ItemStyle Font-Names="Arial" Font-Size="Smaller" />
</asp:CommandField>
remove the above <asp:commandFiield....> </asp:CommandField>
and select your Gridveiw.In Gridview Events double click on RowDeleting event..
Author: gdswati
Company URL: http://www.dotnetspark.com
Posted Date: 24/05/2010
no change yet...I dont know why this is not working...
I was having same problem with my RowUpdated...even that was not getting
triggered after my row was updated...so I wrote different logic..after trying for
hours...and now same thing is happening with RowDeleted.
Author: Syed Shakeer Hussain
http://www.dotnetspark.com
Posted Date: 24/05/2010
Company URL:
Hi ,
send code to my emial id
Author: gdswati
Company URL: http://www.dotnetspark.com
Posted Date: 25/05/2010
Thanks a lott Sahkeer...my delete function is working now. Actually, in delete, my
id was returning null value and thts the reason it was not deleting any record.
Author: Pradip
Company URL: http://www.pmbodar.somee.com
Posted Date: 29/05/2010
Hello frnds !!
This code use to successfully in edit but my record is not update successfully.
I don't know how it..error is not occur.
pls..somebody help me..Thanx in Advance !!
My Update code is.....
GridViewRow row= (GridViewRow)GridView1.Rows[e.RowIndex];
Label lbl = (Label)row.FindControl("no");
TextBox ttitle = (TextBox)row.FindControl("t1");
TextBox thead = (TextBox)row.FindControl("t2");
16 of 21
7/7/2010 4:57 PM
How to Edit,Update,Delete in Gridview - C#, ASP.Net, VB.Net
http://www.dotnetspark.com/kb/643-how-to-editupdatedelete-gridvi...
TextBox tdetail = (TextBox)row.FindControl("t3");
TextBox timage = (TextBox)row.FindControl("t4");
GridView1.EditIndex = -1;
con.ExecuteCommand("update detail set title='" + ttitle.Text + "',head='" +
thead.Text + "',detail='" + tdetail.Text + "',image='" + timage.Text + "' where
no=" + lbl.Text + "");
filldata();
Author: gdswati
Company URL: http://www.dotnetspark.com
Posted Date: 01/06/2010
Pradip,
Check this code and see if this helps...
// SQL Update CommandSqlCommand
SqlCommand mySqlUpdate = new SqlCommand("Update bod_Items set
invItemDesc = @description, invItemQty = @quantity, invItemAmt = @amount,
invItemSerNum = @serNum where cInvNum = '" +
Request.QueryString["InvoiceNumber"].ToString() + "' and itemNum =
@itemNum", myConnection);
//Bound field
TextBox txtQuantity =
(TextBox)grdItems_edit.Rows[e.RowIndex].Cells[1].Controls[0];
//template field - Description
grdItems_edit.Rows[e.RowIndex].Cells[0].FindControl("txtDescription");
TextBox txtDescription =
(TextBox)grdItems_edit.Rows[e.RowIndex].Cells[2].FindControl("txtDescription");
//bound field
TextBox txtSerNum =
(TextBox)grdItems_edit.Rows[e.RowIndex].Cells[3].Controls[0];
//template field
grdItems_edit.Rows[e.RowIndex].Cells[4].FindControl("txtAmt");
TextBox txtAmt =
(TextBox)grdItems_edit.Rows[e.RowIndex].Cells[4].FindControl("txtAmt");
// parameters passed to the SQL Update
mySqlUpdate.Parameters.Add("@quantity", SqlDbType.VarChar).Value =
txtQuantity.Text;
mySqlUpdate.Parameters.Add("@description", SqlDbType.VarChar).Value =
txtDescription.Text;
mySqlUpdate.Parameters.Add("@serNum", SqlDbType.VarChar).Value =
txtSerNum.Text;
mySqlUpdate.Parameters.Add("@amount", SqlDbType.VarChar).Value =
txtAmt.Text;
mySqlUpdate.Parameters.Add("@itemNum", SqlDbType.Int).Value =
Convert.ToInt32(grdItems_edit.DataKeys[e.RowIndex].Values[0].ToString());
mySqlUpdate.ExecuteNonQuery();
Author: Sameer
Company URL: http://www.dotnetspark.com
Posted Date: 03/06/2010
How to add a new empty row in a Datagridview? Using Button event, i am talking
about unbound datagrid.
17 of 21
7/7/2010 4:57 PM
How to Edit,Update,Delete in Gridview - C#, ASP.Net, VB.Net
http://www.dotnetspark.com/kb/643-how-to-editupdatedelete-gridvi...
Author: gdswati
Company URL: http://www.dotnetspark.com
Posted Date: 03/06/2010
Sameer,
you can add textboxes and a Add button next to it. In the event handler for add
button, insert the data from the textboxes in your table and then populate the
grid again.
let me know if you have any questions.
Author: gdswati
Company URL: http://www.dotnetspark.com
Posted Date: 03/06/2010
Sameer,
you can add textboxes and a Add button next to it. In the event handler for add
button, insert the data from the textboxes in your table and then populate the
grid again.
let me know if you have any questions.
Author: Sameer
Company URL: http://www.dotnetspark.com
Posted Date: 03/06/2010
Thanks Swati,
I did it and it works. One more problem is,
Can i insert all the values in datagridview(in DataTable) into the database?
Author: gdswati
Company URL: http://www.dotnetspark.com
Posted Date: 03/06/2010
Sameer,
How is your gridview setup?
When you say inserting all values in datagridview into database...Do you mean
inserting values in all rows and columns from your gridview?
Author: Sameer
Company URL: http://www.dotnetspark.com
Posted Date: 03/06/2010
Not exactly, My datagridview contains some 20 columns, say i am giving values 4
to 5 rows for all the columns, how can i store the values into the database? I am
using OLEDB as my back end database.
Author: gdswati
Company URL: http://www.dotnetspark.com
Posted Date: 03/06/2010
Not sure if I am understanding it correctly.
You would change the values for one row at a time right? So cant you use
Update?
Author: Sameer
Company URL: http://www.dotnetspark.com
Posted Date: 04/06/2010
I am giving all the values simultaneously into the grid. Well using Update is a
good suggestion i will try it, any way thanks a lot for your help swati.
Author: Amala
18 of 21
Company URL: http://www.dotnetspark.com
7/7/2010 4:57 PM
How to Edit,Update,Delete in Gridview - C#, ASP.Net, VB.Net
http://www.dotnetspark.com/kb/643-how-to-editupdatedelete-gridvi...
Posted Date: 29/06/2010
Hello,Ur codings heleps me lot..Thanks for publishing ur code.But i got some
problem.when i click update, all data which r present in gridview r duplicated once
again
But when the page is loaded the duplicated data was removed , the data was
updated ..and i got a proper result.Herewith i send my code
---------------------------------------------------Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load
myset = New DataSet
conn = New SqlConnection()
conn.ConnectionString = "initial catalog=home;user id=sa;pwd=''"
conn.Open()
mycomm = New SqlCommand()
mycomm.Connection = conn
conn.Close()
End Sub
Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles
GridView1.RowUpdating
Dim row As GridViewRow
Dim Exp As TextBox
Dim Amount As TextBox
row = GridView1.Rows(e.RowIndex)
Exp = row.FindControl("Textbox1")
Amount = row.FindControl("Textbox2")
GridView1.EditIndex = -1
conn.Open()
mycomm.CommandText = "update get set Amount='" & Amount.Text & "' where
Expenses= '" & Exp.Text & "'"
mycomm.ExecuteNonQuery()
bind()
conn.Close()
End Sub
Sub bind()
myadapter = New SqlDataAdapter("select * from get where
datename(Month,Currentdate)='" & DropDownList1.SelectedItem.Text & "'", conn)
myadapter.Fill(myset, "get")
GridView1.DataSource = myset.Tables(0)
GridView1.DataBind()
conn.Close()
End Sub
Author: Syed Shakeer Hussain
http://www.dotnetspark.com
Posted Date: 29/06/2010
Company URL:
Hi Amala,
use IsPostBack Property in PageLoad,your problem will solve..I had written the
code below,try it.
--------------------------Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
19 of 21
7/7/2010 4:57 PM
How to Edit,Update,Delete in Gridview - C#, ASP.Net, VB.Net
http://www.dotnetspark.com/kb/643-how-to-editupdatedelete-gridvi...
Handles Me.Load
conn = new SqlConnection("your connection string");
If Not Page.IsPostBack then
bind()
End If
End PageLoad
--------------------------------Below code is same what you had written
Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles
GridView1.RowUpdating
Dim row As GridViewRow
Dim Exp As TextBox
Dim Amount As TextBox
row = GridView1.Rows(e.RowIndex)
Exp = row.FindControl("Textbox1")
Amount = row.FindControl("Textbox2")
GridView1.EditIndex = -1
conn.Open()
mycomm.CommandText = "update get set Amount='" & Amount.Text & "' where
Expenses= '" & Exp.Text & "'"
mycomm.ExecuteNonQuery()
bind()
conn.Close()
End Sub
--------------Sub bind()
conn.Open()
myadapter = New SqlDataAdapter("select * from get where
datename(Month,Currentdate)='" & DropDownList1.SelectedItem.Text & "'", conn)
myadapter.Fill(myset, "get")
GridView1.DataSource = myset.Tables(0)
GridView1.DataBind()
conn.Close()
End Sub
Author: Amala
Company URL: http://www.dotnetspark.com
Posted Date: 01/07/2010
Thanks for ur reply sir.....i tried ,but i got the same error
Post Comment
You must Sign In To post reply
Read also another
Resources
from the
CASCADING
Referential
Integrity in
same
Author
SqlServer
20 of 21
Related Resource From
The Same
Category
Implement
Multilingual
in ASP.NET
Web Site using globalization.
7/7/2010 4:57 PM
How to Edit,Update,Delete in Gridview - C#, ASP.Net, VB.Net
http://www.dotnetspark.com/kb/643-how-to-editupdatedelete-gridvi...
Encrypt and Decrypt a Password
using EncryptByPassPhrase and
DecryptByPassPhrase
Online Payments Using PayPalIntegration with ASP.NET
Chat Application Using Application
How to get DATE without DATE TIME
using SQL SERVER?
State Object
Create thumbnail of a Image
Find all Primary and Foreign Keys In
RowCommand Event in GridView
A Database
Scrolling Text on Submit Button
usign javascript?
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here
Hall of Fame
21 of 21
Twitter
Terms of Service
Privacy Policy
Contact Us
Archives
Tell A Friend
7/7/2010 4:57 PM