RowCommand Event In GridView In Asp.Net
Here we are binding a GridView and using RowCommand event in GridView in Asp.net C#.
In RowCommand event you can use any CommandName of Button as you want.
Points Of Remember:
1. Fire GridView's RowCommand event.
2. Place LinkButtons in ItemTemplate of Gridview's column.
3. Set CommandName propery of LinkButtons.
4. Use CommandArgument for bind value.
5. Add namespace System.Data and System.Data.SqlClient in your C# page.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" CellPadding="4"
OnRowCommand="GridView1_RowCommand" Width="600px" ForeColor="#333333">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LB1" runat="server" CommandName="add">Add</asp:LinkButton>
<asp:LinkButton ID="LB2" runat="server" CommandName="remove"
CommandArgument='<%#Eval("ID") %>'>Remove</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Branch" HeaderText="Branch" />
<asp:BoundField DataField="City" HeaderText="City" />
</Columns>
<HeaderStyle BackColor="#7961da" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
</asp:GridView>
</div>
</form>
</body>
</html>
C# Codes :
using System.Data;
using System.Data.SqlClient;
public partial class GridView_test_rowcommandevent
:
System.Web.UI.
Page
{
SqlConnection con = new SqlConnection( @"Data Source=JITESH-PC\SQL;Initial
Catalog=db_Student;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridView();
}
}
//method for binding GridView
protected void BindGridView()
{
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(
"Select
ID,Name,Branch,City from tbl_student"
, con);
con.Open();
da.Fill(dt);
con.Close();
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
string query = "";
if (e.CommandName == "add")
{
query = "insert into tbl_Student(Name,Branch,City) values('Rahul','ECE','Jaipur')";
}
else if (e.CommandName == "remove")
{
// find student id of clicked row
string id= e.CommandArgument.ToString();
query = "delete from tbl_Student where ID="+id+"";
}
SqlCommand cmd = new SqlCommand
(query,
con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
BindGridView();
}
}