How to delete multiple row in database using gridview in asp.net?
<asp:gridview id="GridView1" runat="server" autogeneratecolumns="False" xmlns:asp="#unknown">
DataKeyNames="Emp_ID" style="text-align: center">
<columns> <asp:boundfield datafield="Emp_ID" headertext="Emp_ID" insertvisible="False" readonly="True">
SortExpression="Emp_ID" />
<asp:boundfield datafield="FName" headertext="FName" sortexpression="FName">
<asp:boundfield datafield="LName" headertext="LName" sortexpression="LName">
<asp:boundfield datafield="Address" headertext="Address" sortexpression="Address">
<asp:boundfield datafield="E-Mail" headertext="E-Mail" sortexpression="E-Mail">
<asp:templatefield headertext="Action">
<itemtemplate>
<asp:checkbox id="chkSelect" runat="server" oncheckedchanged="chkStatus_OnCheckedChanged" value="Emp_ID" autopostback="true">
Quote:
protected void btnupdt_Click(object sender, EventArgs e)
{
string ids = "";
foreach (GridViewRow di in GridView1.Rows)
{
CheckBox chkBx = (CheckBox)di.FindControl("chkSelect");
if (chkBx != null && chkBx.Checked)
{
ids = ids + GridView1.DataKeys[di.RowIndex].Value.ToString() + " ";
}
}
if (!string.IsNullOrEmpty(ids))
{
string str = "update Emp_Mgt set FName='" + txtfrstnm.Text + "',LName='" + txtlstnm.Text + "',Address='" + txtadrs.Text + "',[E-Mail]='" + txtemil.Text + "' where Emp_Id=" + ids;
SqlCommand cmd = new SqlCommand(str, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
loadgrid();
lblchk.Text = "("+ids+") Row Is Update....!";
}
protected void btndlt_Click(object sender, EventArgs e)
{
string ids = "";
foreach (GridViewRow di in GridView1.Rows)
{
CheckBox chkBx = (CheckBox)di.FindControl("chkSelect");
if (chkBx != null && chkBx.Checked)
{
ids = ids + GridView1.DataKeys[di.RowIndex].Value.ToString() + ",";
}
}
if (!string.IsNullOrEmpty(ids))
{
SqlCommand cmd = new SqlCommand("delete from Emp_Mgt where Emp_ID IN (" + ids.Trim(',') + ")", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
loadgrid();
lblchk.Text = "(" + ids.Trim(',') + ") Rows Are Delete....!";
}
protected void chkStatus_OnCheckedChanged(object sender, EventArgs e)
{
SqlDataReader sdr;
string ids = "";
foreach (GridViewRow di in GridView1.Rows)
{
CheckBox chkBx = (CheckBox)di.FindControl("chkSelect");
if (chkBx != null && chkBx.Checked)
{
ids = ids + GridView1.DataKeys[di.RowIndex].Value.ToString() ;
}
}
if (!string.IsNullOrEmpty(ids))
{
string str = "select FName,LName,Address,[E-Mail] from [emp_mgt] where Emp_Id=" + ids;
SqlCommand cmd = new SqlCommand(str, con);
con.Open();
sdr = cmd.ExecuteReader();
while (sdr.Read())
{
txtfrstnm.Text = sdr["FName"].ToString();
txtlstnm.Text = sdr["LName"].ToString();
txtadrs.Text = sdr["Address"].ToString();
txtemil.Text = sdr["E-Mail"].ToString();
}
con.Close();
}
}