如何获取datagridview C#的多个复选框列的行索引
本文关键字:复选框 索引 何获取 获取 datagridview | 更新日期: 2023-09-27 18:21:01
我正在尝试删除未绑定数据网格视图中所有标记/检查的行。复选框列是通过程序添加的。我知道我必须使用
RequestedEmpGrid.Rows.Remove(RequestedEmpGrid.Rows[ForRequestRow.Index]);
以从网格中删除该行。但是,我在获取datagridview中多个选中行的行索引时遇到了问题。我的循环不起作用。帮助
//REMOVE ALL CHECKED
foreach (DataGridViewRow ForRequestRow in RequestedEmpGrid.Rows)
{
if (Convert.ToBoolean(ForRequestRow.Cells[MarkColumn.Name].Value) == true)
{
RequestedEmpGrid.Rows[ForRequestRow.Index].Selected = true;
RequestedEmpGrid.Rows.Remove(RequestedEmpGrid.Rows[ForRequestRow.Index]);
}
}
为什么不试试
RequestedEmpGrid.Rows.Remove(ForRequestRow)
它只会从网格视图中删除该行,而不会从数据源中删除,因此不要重新绑定网格视图,因为它会再次添加删除的行。
如果您也想从数据源中删除,只需从数据库中删除选定的行,然后重新绑定网格视图。
您可以尝试以下代码:
foreach (DataGridViewRow requestRow in RequestedEmpGrid.Rows)
{
if (Convert.ToBoolean(requestRow.Cells[MarkColumn.Name].Value))
{
RequestedEmpGrid.Rows.Remove(requestRow);
}
}
或者这个:
foreach (DataGridViewRow requestRow in RequestedEmpGrid.Rows)
{
if (Convert.ToBoolean(requestRow.Cells[MarkColumn.Name].Value))
{
RequestedEmpGrid.Rows.RemoveAt(requestRow.Index);
}
}
更新:怎么样?
for (int i = RequestedEmpGrid.Rows.Count; i >= 0; i--)
{
var row = RequestedEmpGrid.Rows[i];
if (Convert.ToBoolean(row.Cells[MarkColumn.Name].Value))
{
RequestedEmpGrid.Rows.RemoveAt(i);
}
}