如果不用DataSet和Adapter绑定数据,自己在Load事件里读取一个DataTable绑定数据到DataGridView,删除数据时就不能再利用DataSet了,需要自己取选中行的关键字段值,构建sql语句执行
正常是利用UserDeletingRow和UserDeletedRow事件的,但是如果选择了多行,UserDeletingRow事件会被执行多次,这里有一个很怪的问题,我现在没时间查资料是什么原因了,先记录下来,回头再查
如果在第一次执行UserDeletingRow事件时,做了批量操作,进入UserDeletedRow事件后,执行了重新绑定数据的操作,UserDeletingRow事件会被中断,也就是只执行一次
private int deleteCount = 0;
private int selectedRowCount = 0;
private bool cancelDelete = false;
private int eventCount = 0;
private void dataGridView1_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
{
//UserDeletingRow事件,如果第一次没有取消,执行了批量操作,就只执行一次,否则会执行选中行数-1次。。。
eventCount++;
deleteCount++;
//MessageBox.Show(String.Format("begin: eventCount = {3}, deleteCount = {0}, selectedRowCount = {1}, cancelDelete = {2}", deleteCount, selectedRowCount, cancelDelete, eventCount));
//第一次执行UserDeletingRow事件时,提醒是否要删除数据,批量删除所有选中行
if (deleteCount == 1)
{
//取总共要删除的行数,即UserDeletingRow将要执行的次数
selectedRowCount = dataGridView1.SelectedRows.Count - 1;
//提醒是否要取消操作
cancelDelete = SaleClass.CancelDelte();
if (cancelDelete)
{
e.Cancel = true;
}
else
{
//批量删除所有选中行,如果删除失败,取消后续所有操作
if (!DeleteRows())
{
cancelDelete = true;
e.Cancel = true;
}
}
}
//MessageBox.Show(String.Format("before: deleteCount = {0}, selectedRowCount = {1}, cancelDelete = {2}", deleteCount, selectedRowCount, cancelDelete));
//最后一次执行UserDeletingRow时,要恢复计数器,以备下一次点击delete键
if (deleteCount == selectedRowCount)
{
deleteCount = 0;
selectedRowCount = 0;
cancelDelete = false;
}
//MessageBox.Show(String.Format("end: deleteCount = {0}, selectedRowCount = {1}, cancelDelete = {2}", deleteCount, selectedRowCount, cancelDelete));
}
private void dataGridView1_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
{
FillList(); //重新填充数据
}