0
DataTable dt = ((DataTable)dataGridView1.DataSource).Copy();

After i delete rows from DataGridview I am getting error while reading dt. "DeletedRowInaccessibleException"

How can i copy not deleted rows in to datatable?

Koray
  • 373
  • 4
  • 12

2 Answers2

2
DataTable gridTable = (DataTable)dataGridView1.DataSource;

//you can call AcceptChanges() if you want !

//create data table with the same schema as gridTable !
DataTable dt = gridTable.Clone();

foreach(DataRow row in gridTable.Rows)
{
    if(row.RowState == DataRowState.Deleted)
       continue;

    //import every row from the gridTable to the new DataTable.
    dt.ImportRow(row);
}

Here one way to do it.

mybirthname
  • 17,949
  • 3
  • 31
  • 55
2

You asked to not copy the Deleted rows, then you could write

DataTable source = (DataTable)dataGridView1.DataSource;
DataTable dt = source.Rows
                     .Cast<DataRow>()
                     .Where(x => x.RowState != DataRowState.Deleted)
                     .CopyToDataTable();

This solution uses the IEnumerable extensions Cast to create a sequence of DataRows to which is applied the Where condition checking the RowState.
Then the sequence is rematerialized in a DataTable using CopyToDataTable extension

Community
  • 1
  • 1
Steve
  • 213,761
  • 22
  • 232
  • 286