Delete Multiple Rows in GridView using ChekBox in ASP.NET
21:49
In this example i am explaining how to delete multiple rows records with Chekbox using C#.Net in Asp.Net
1. Design the aspx page like below
1. Design the aspx page like below
<%@ Page
Language="C#"
AutoEventWireup="true"
CodeFile="Default.aspx.cs"
Inherits="_Default"
%>
<!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></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td colspan="2">
<asp:GridView ID="grid" runat="server"
AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<input name="chek" type="checkbox"
value='<%#Eval("Emp_Id")%>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Employee
Id" DataField="Emp_Id" />
<asp:BoundField HeaderText="Employee
Name" DataField="Emp_Name" />
<asp:BoundField HeaderText="Salary"
DataField="Emp_Salary"
/>
</Columns>
<SelectedRowStyle
HorizontalAlign="Center"
VerticalAlign="Middle"
/>
</asp:GridView><br />
<asp:Button ID="btndelete"
runat="server"
Text="Delete"
onclick="btndelete_Click"
/>
<br />
<asp:Label ID="lblmsg" runat="server"
Text=""></asp:Label>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
The Page shows Like Below
2.Add the below code in .cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class _Default :
System.Web.UI.Page
{
protected void
Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
public void
BindData()
{
SqlConnection con = new
SqlConnection("server=ADMINISTRATOR00;database=Acadamics;uid=ACMCPRJ;pwd=projects");
SqlDataAdapter da = new
SqlDataAdapter("select
* from Employee1", con);
SqlCommandBuilder cmb = new
SqlCommandBuilder(da);
DataTable table = new
DataTable();
da.Fill(table);
grid.DataSource = table;
grid.DataBind();
}
protected void
btndelete_Click(object sender, EventArgs e)
{
string empid = Request.Form["chek"];
SqlConnection con = new
SqlConnection("server=ADMINISTRATOR00;database=Acadamics;uid=ACMCPRJ;pwd=projects");
SqlCommand cmd = new
SqlCommand("Delete
Employee1 where Emp_Id in (" + empid + ")",
con);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
string msg = "";
if (i != 0)
{
msg = "Records deleted
successfully..";
}
else
{
msg = "Records deletion failed..";
}
lblmsg.Text = msg.ToString();
BindData();
}
}
3.Then run the application or press F5.
The page shows like below
Select deleted records using chekbox and click on delete button. then the output will show below..
0 comments :