从DataGridView中删除选定的行

时间:2016-04-29 19:27:18

标签: c# datagridview casting

我正在尝试从DataGridView中删除所选行,但我收到以下错误消息:

  

指定的演员表无效。

在这行代码中:

this.DGV_INVOICE.Rows.Cast<DataGridViewRow>().Where(ROW => (bool?)ROW.Cells[0].Value == true).ToList().ForEach(x => { this.DGV_INVOICE.Rows.Remove(x); });

尝试删除所有选定行的第二种方法:

foreach (DataGridViewRow RowToDelete in DGV_INVOICE.Rows)
{
    object Cell = RowToDelete.Cells["Edit_Checkbox"].Value;

    if (Cell.ToString() == "True")
    {
        // Allow user to delete record from invoice
        DGV_INVOICE.Rows.Remove(RowToDelete);
    }
}

1 个答案:

答案 0 :(得分:3)

向后循环访问DataGridView的.Rows集合,以便在删除时不会丢失索引

for (int i = DGV_INVOICE.Rows.Count - 1; i >= 0; i--)
{
    object Cell = DGV_INVOICE.Rows[i].Cells["Edit_Checkbox"].Value;

    if (Cell.ToString() == "True")
        DGV_INVOICE.Rows.RemoveAt(i);
}