17

I want to get a DataTable from DataGridView of the Grid values.

In other words DataTable same as DataGridView Values

Charles Clayton
  • 17,005
  • 11
  • 87
  • 120
Mobin
  • 4,870
  • 15
  • 45
  • 51

4 Answers4

49

Might be a nicer way to do it but otherwise it would be fairly trivial to just loop through the DGV and create the DataTable manually.

Something like this might work:

DataTable dt = new DataTable();
foreach(DataGridViewColumn col in dgv.Columns)
{
   dt.Columns.Add(col.Name);    
}

foreach(DataGridViewRow row in dgv.Rows)
{
    DataRow dRow = dt.NewRow();
    foreach(DataGridViewCell cell in row.Cells)
    {
        dRow[cell.ColumnIndex] = cell.Value;
    }
    dt.Rows.Add(dRow);
}
Hans Olsson
  • 54,199
  • 15
  • 94
  • 116
  • 2
    You may want to preserve the column types in the cloned DataTable, by adding `col.CellTemplate.ValueType` argument to the `dt.Columns.Add` in line 4. (I got FormatException without this thing, when processing the copied table.) – P.W. Sep 16 '19 at 17:00
13

You can cast the DataSource object from the DataGridView to a DataTable

DataTable dt = new DataTable();
dt = (DataTable)dataGridView1.DataSource;
Trenton Wallace
  • 131
  • 1
  • 2
  • 6
    It should be noted that this will not work if the DataSource is a BindingList, though I was very hopeful. – Van Amburg Jun 04 '15 at 16:12
5

you can use the following code also, this code fill not effect on your DataGridView when you do some add or delete rows in the datatable

DataTable dt = new DataTable();
dt = Ctype(dataGridView1.DataSource,DataTable).copy();
Vishal Gavle
  • 369
  • 2
  • 5
0

You can try as follow:

using System.Data;
using System.Windows.Forms;

namespace BLL
{
    public class Class_DataGridview_To_DataTable
    {
        public static DataTable UDF_Convert_DataGridView_To_Datatable(DataGridView ImpGrd)
        {
            DataTable ExportDataTable = new DataTable();
            foreach (DataGridViewColumn col in ImpGrd.Columns)
            {
                ExportDataTable.Columns.Add(col.Name);
            }

            foreach (DataGridViewRow row in ImpGrd.Rows)
            {
                DataRow dRow = ExportDataTable.NewRow();
                foreach (DataGridViewCell cell in row.Cells)
                {
                    dRow[cell.ColumnIndex] = cell.Value;
                }
                ExportDataTable.Rows.Add(dRow);
            }

            return ExportDataTable;
        }
    }
}
Ali NajafZadeh
  • 51
  • 7
  • 20