protected void btnDelete_Click(object sender, EventArgs e)
{
StringCollection idCollection = new StringCollection();
string strID = string.Empty;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chkDelete = (CheckBox)
GridView1.Rows[i].Cells[0].FindControl("chkSelect");
if (chkDelete != null)
{
if (chkDelete.Checked)
{
strID = GridView1.Rows[i].Cells[1].Text;
idCollection.Add(strID);
}
}
}
DeleteMultipleRecords(idCollection);
GridView1.DataBind();
}
private void DeleteMultipleRecords
(StringCollection idCollection)
{
SqlConnection con = new SqlConnection(strConnection);
SqlCommand cmd = new SqlCommand();
string IDs = "";
foreach (string id in idCollection)
{
IDs += id.ToString() + ",";
}
try
{
string strIDs =
IDs.Substring(0, IDs.LastIndexOf(","));
string strSql = "Delete from Details
WHERE ID in (" + strIDs + ")";
cmd.CommandType = CommandType.Text;
cmd.CommandText = strSql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
string errorMsg = "Error in Deletion";
errorMsg += ex.Message;
throw new Exception(errorMsg);
}
finally
{
con.Close();
}
}