private void buttonDelete_Click(object sender, EventArgs e)
{
DialogResult = MessageBox.Show("确定删除这些数据么?", "提示", MessageBoxButtons.YesNo);
List<int> list = new List<int>();
if (DialogResult == DialogResult.Yes)
{
for (int i = 0; i < studentList.Rows.Count; i++)
{
//获取选中的数据
if ((bool)studentList.Rows[i].Cells["checks"].EditedFormattedValue == true)
{
//获取被选中数据的主键
int n = int.Parse(studentList.Rows[i].Cells["StuId"].Value.ToString());
list.Add(n);
}
}
int count = 0;
//启动事务
using (SqlConnection conn = new SqlConnection(SqlHelper.connStr))
{
//事务实通过conn开启,
conn.Open();
SqlTransaction trans = conn.BeginTransaction();
//sqlcommand 执行事务
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.Transaction = trans;
try
{
foreach (int s in list)
{
cmd.CommandText = "delete from StuInfo where StuId=@StuId";
SqlParameter pares = new SqlParameter("StuId", s);
cmd.Parameters.Clear();
cmd.Parameters.Add(pares);
count += cmd.ExecuteNonQuery();
}
trans.Commit();
}
catch (Exception ex)
{
trans.Rollback();
MessageBox.Show(ex.Message, "错误提示");
return;
}
}
if (count == list.Count)
{
//手动刷新界面显示
DataTable data = studentList.DataSource as DataTable;
string idStr = string.Join(",", list);
DataRow[] rows = data.Select("StuId in (" + idStr + ")");
foreach(DataRow row in rows)
{
data.Rows.Remove(row);
}
studentList.DataSource = data;
MessageBox.Show("删除成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
}
// 刷新datagridview显示
studentList.Refresh();
}
