请问一下,我想实现对查询出的行,实现选中后批量删除的效果,目前是采用以下方法,及在CellMouseClick事件下面,但实际运行时,还是单行删除的效果,请看看哪里有什么问题吗,谢谢;
private void DeleteSelectedRows()
{
List<int> idsToDelete = new List<int>();
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
int id = Convert.ToInt32(row.Cells["id"].Value);
idsToDelete.Add(id);
}
if (idsToDelete.Count > 0)
{
using (SqlConnection conn = new SqlConnection("server=192.168.100.247;database=Whmesinfo;user=sa;password=whyy@2021"))
{
conn.Open();
foreach (int id in idsToDelete)
{
string datadel = string.Format("delete from w_prohourcount where id = {0} ",id);
using (SqlCommand comm = new SqlCommand(datadel, conn))
{
int rowsAffected = comm.ExecuteNonQuery();
if (rowsAffected == 0)
{
MessageBox.Show("部分删除失败");
break;
}
}
}
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
// 删除选中的行(仅在所有删除操作成功后)
foreach (int id in idsToDelete)
{
dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows.Cast<DataGridViewRow>().First(r => Convert.ToInt32(r.Cells["id"].Value) == id).Index);
}
}
}
}
private List<int> selectedRowIds = new List<int>();
private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.RowIndex >= 0 && (e.ColumnIndex == dataGridView1.Columns["DeleteColumn"].Index || e.ColumnIndex == dataGridView1.Columns["UpdateColumn"].Index))
{
// 删除按钮被点击
if (e.ColumnIndex == dataGridView1.Columns["DeleteColumn"].Index)
{
int id = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["id"].Value);
if (selectedRowIds.Contains(id))
{
selectedRowIds.Remove(id);
}
else
{
selectedRowIds.Add(id);
}
}
// 修改按钮被点击
if (e.ColumnIndex == dataGridView1.Columns["UpdateColumn"].Index)
{
。。。。。。。。。。。。。
}
}
}