How to make a DataTable from DataGridView without any Datasource?
Asked Answered
E

4

17

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

In other words DataTable same as DataGridView Values

Evesham answered 24/6, 2010 at 10:15 Comment(1)
Can't you just instantiate a new datatable and set it as the datasource of the gridview?Framing
K
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);
}
Krueger answered 24/6, 2010 at 10:34 Comment(1)
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.)Sse
C
13

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

DataTable dt = new DataTable();
dt = (DataTable)dataGridView1.DataSource;
Chloramine answered 15/5, 2012 at 15:55 Comment(1)
It should be noted that this will not work if the DataSource is a BindingList<T>, though I was very hopeful.Mediator
H
4

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();
Horrendous answered 10/11, 2012 at 9:18 Comment(0)
S
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;
        }
    }
}
Shantell answered 24/9, 2021 at 12:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.