Koray
Koray

Reputation: 407

Copying rows from datagridwiew to datatable

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?

Upvotes: 0

Views: 106

Answers (2)

mybirthname
mybirthname

Reputation: 18127

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.

Upvotes: 2

Steve
Steve

Reputation: 216302

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

Upvotes: 2

Related Questions