TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
C# Corner
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Deleting a Record by using RowCommand
Sreekanth Reddy
Nov 05, 2015
35.2
k
0
1
facebook
twitter
linkedIn
Reddit
WhatsApp
Email
Bookmark
In this article you will learn how to Deleting a Record by using RowCommand.
Look at given point:
RowCommand is one of the event to Gridveiw.
This event fires whenever an action performed(Ex: button is clicked ) on Gridveiw control.
To perform any operations with rowcommand in Gridveiw we need to use a property known as “commandname”.
CommandName property is used to a button control.
Example:
commandname=”abc”.
In the above line abc is commandname.
Utilization of a commandname in itemtemplate for button is shown below.
Now why commandname?
CommandName is used to differentiate two button type controls within Gridveiw as shown below.
Observe the following snippet:
For the above code we will get the following design:
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;
namespace
WebApplication1
{
public
partial
class
WebForm2 : System.Web.UI.Page
{
SqlConnection con =
new
SqlConnection(
"server=.;database=abc;trusted_connection=true"
);
protected
void
Page_Load(
object
sender, EventArgs e)
{
if
(!IsPostBack)
{
bind();
}
}
public
void
bind()
{
SqlCommand cmd =
new
SqlCommand(
"select * from employee"
, con);
SqlDataAdapter da =
new
SqlDataAdapter(cmd);
DataSet ds =
new
DataSet();
da.Fill(ds,
"con"
);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected
void
GridView1_RowCommand(
object
sender, GridViewCommandEventArgs e)
{
if
(e.CommandName ==
"comdel"
)
{
int
l = Convert.ToInt32(e.CommandArgument);
con.Open();
SqlCommand cmd =
new
SqlCommand(
"delete from employee where eno=@a"
, con);
cmd.Parameters.AddWithValue(
"@a"
, l);
int
i = cmd.ExecuteNonQuery();
if
(i == 1)
{
Response.Write(
"Record deleted"
);
bind();
}
else
{
Response.Write(
"Recodrd not deleted..."
);
}
Page_Load(sender, e);
}
}
}
}
Explanation on e.commandargument:
In the above code I used the following line in rowcommand event.
if
(e.CommandName ==
"comdel"
)
{
int
l = Convert.ToInt32(e.CommandArgument);
…..
…
…
}
e.commandargument specifies the employee number. Observe the following aspx code snippet.
If still any doubts plzz feel free to ask.
Thank you.
Delete a Record
RowCommand
ASP.NET
Next Recommended Reading
Display Records from Database to DataGridView using DataReader