本文介绍了删除DataGridView(表)中的多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个Datable"myTable",它与DataGridView"dgv"绑定.DataGridView"dgv"具有一个复选框列.我的目标是删除按钮事件中选中的行.数据表当然会更新.现在我的代码仅适用于删除一行,而不适用于多行.
I have a datable "myTable", which is bind with a DataGridView "dgv". The DataGridView "dgv" has a checkbox column. My goal is to delete rows checked in a button event. The datatable is updated of course.Now my code is only working for deleting one row not for multiple rows.
感谢您的帮助.
private void btnDel_Click(object sender, EventArgs e)
{
try
{
if (dgv.RowCount>0)
{
foreach (DataGridViewRow row in dgv.Rows)
{
DataGridViewCheckBoxCell check = row.Cells[0] as DataGridViewCheckBoxCell;
if (check.Value != null)
{
if ((bool)check.Value)
{
DataRowView currentDataRowView = (DataRowView)dgv.CurrentRow.DataBoundItem;
DataRow dataRow = currentDataRowView.Row;
int n = dgv.CurrentRow.Index;
int intID = Convert.ToInt32(dgv.Rows[n].Cells[0].Value);
myTable.Rows.Remove(dataRow);
dgv.DataSource = myTable;
Int32 intVal = Convert.ToInt32(row.Cells[1].Value);
if (intVal == intID)
{
check.Value = null;
}
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
推荐答案
我找到了解决方案.该错误是由
I found the solution. The error was caused by
DataRowView currentDataRowView = (DataRowView)dgv.CurrentRow.DataBoundItem;
currentDataRowView不是选中的行.正确的代码是:
currentDataRowView is not the checked row.The correct code is:
List<DataRow> toDelete = new List<DataRow>();
for (int i = 0; i < dgv.Rows.Count; i++)
{
{
DataGridViewRow row = dgv.Rows[i];
DataGridViewCheckBoxCell check = row.Cells[0] as DataGridViewCheckBoxCell;
if (check.Value != null && (bool)check.Value)
{
DataRow dataRow = (row.DataBoundItem as DataRowView).Row;
toDelete.Add(dataRow);
}
}
}
toDelete.ForEach(row => row.Delete());
感谢大家的帮助.
这篇关于删除DataGridView(表)中的多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!