Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataGridView selected rows to DataTable

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;
                }
            }
like image 203
Naourass Derouichi Avatar asked Oct 28 '13 16:10

Naourass Derouichi


People also ask

How to get selected row from DataGridView?

To get the selected rows in a DataGridView controlUse the SelectedRows property. To enable users to select rows, you must set the SelectionMode property to FullRowSelect or RowHeaderSelect.

How do I pass DataGridView selected row value to textbox in another form?

Text = Convert. ToString(frm. DataGridView1[1, row]. Value);

How to select cell in DataGridView c#?

CurrentCell = dataGridView1. Rows[rowindex]. Cells[columnindex].


2 Answers

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;
                                   //^^^^^^^^^^^
     }
 }
like image 56
Habib Avatar answered Sep 30 '22 15:09

Habib


DataTable dt = ((DataTable)dgvQueryResult.DataSource).Clone();
foreach (DataGridViewRow row in dgvQueryResult.SelectedRows)
{
    dt.ImportRow(((DataTable)dgvQueryResult.DataSource).Rows[row.Index]);
}
dt.AcceptChanges();
like image 33
Gopal Avatar answered Sep 30 '22 15:09

Gopal