DataGridView selected rows to DataTable

38,296

Solution 1

You have to access SelectedRows like

dt.Rows[i][j] = dataGridView1.SelectedRows[i].Cells[j].Value;

Also its better if your DataTable has the same type as of Cell

DataTable dt = new DataTable();
 foreach (DataGridViewColumn column in dataGridView1.Columns)
    dt.Columns.Add(column.Name, column.CellType); //better to have cell type

So your code would be:

DataTable dt = new DataTable();
foreach (DataGridViewColumn column in dataGridView1.Columns)
    dt.Columns.Add(column.Name, column.CellType); //better to have cell type
for (int i = 0; i < dataGridView1.SelectedRows.Count; i++)
{
     dt.Rows.Add();
     for (int j = 0; j < dataGridView1.Columns.Count; j++)
     {
         dt.Rows[i][j] = dataGridView1.SelectedRows[i].Cells[j].Value;
                                   //^^^^^^^^^^^
     }
 }

Solution 2

DataTable dt = ((DataTable)dgvQueryResult.DataSource).Clone();
foreach (DataGridViewRow row in dgvQueryResult.SelectedRows)
{
    dt.ImportRow(((DataTable)dgvQueryResult.DataSource).Rows[row.Index]);
}
dt.AcceptChanges();
Share:
38,296
Naourass Derouichi
Author by

Naourass Derouichi

Success is not final, failure is not fatal: it is the courage to continue that counts. - Winston Churchill

Updated on February 07, 2020

Comments

  • Naourass Derouichi
    Naourass Derouichi over 4 years

    I'm trying to add only the selected rows of a DataGridView to a DataTable, the code that I'm using always start from the first row even if this one is not selected... Does someone have an idea for how to fix this please?

     DataTable dt = new DataTable("Rapport");
    
                //Generating columns to datatable:
                foreach (DataGridViewColumn column in dataGridView1.Columns)
                    dt.Columns.Add(column.Name, typeof(string));
    
                //Adding selected rows of DGV to DataTable:
                for (int i = 0; i < dataGridView1.SelectedRows.Count; i++)
                {
                    dt.Rows.Add();
                    for (int j = 0; j < dataGridView1.Columns.Count; j++)
                    {
                        dt.Rows[i][j] = dataGridView1[j, i].Value;
                    }
                }
    
  • Naourass Derouichi
    Naourass Derouichi over 10 years
    Thank you Habib, this was very helpfull.