TheRealProgrammer TheRealProgrammer - 27 days ago 9
C# Question

Exporting datagridview selectedrows to a datatable won't work

I want to export all selectedRows from a datagridview to a DataTable. When clicking (selecting) on more than 2 rows, the next error appears:

"An exception error of type System.IndexOutOfRangeException occurred in System.Data.dll."

First, I tried:

DataTable table = new DataTable();
for (int i = 0; i < dataGridView_auswahlen.Rows.Count; i++) {
if (dataGridView_auswahlen.Rows[i].Selected) {
table.Rows.Add( );
for (int j = 0; j < dataGridView_auswahlen.Columns.Count; j++) {
table.Rows[i][j] = dataGridView_auswahlen[j, i].Value;
}
}
}


After that, I modified it in:

DataTable dt = new DataTable(); // create a table for storing selected rows
var dtTemp = dataGridView1.DataSource as DataTable; // get the source table object
dt = dtTemp.Clone(); // clone the schema of the source table to new table
DataTable table = new DataTable();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (dataGridView1.Rows[i].Selected)
{
var row = dt.NewRow(); // create a new row with the schema
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
row[j] = dataGridView1[j, i].Value;
}
dt.Rows.Add(row); // add rows to the new table
}
}


The problem now, is that, my dataGridView is displaying only 1 result. I need to have the full result list in my dataGridView displayed and ONLY the selectedrows to be saved into a DataTable.

Answer

Use this simple code:

var dtSource = dataGridView1.DataSource as DataTable;
var dt = dtSource.Clone();

foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
    dt.ImportRow(dtSource.Rows[row.Index]);
}