Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a DataTable from DataGridView without any Datasource?

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

In other words DataTable same as DataGridView Values

like image 302
Mobin Avatar asked Jun 24 '10 10:06

Mobin


People also ask

How to convert DataGridView into DataTable in c#?

Converting DataGridView to DataTable When the Convert Button is clicked, first the Columns from the DataGridView are used to create a DataTable and then using a loop, data from each Row of DataGridView is inserted into the DataTable in Windows Forms (WinForms) Application using C# and VB.Net.

What is datasource in DataGridView?

The DataGridView class supports the standard Windows Forms data-binding model. This means the data source can be of any type that implements one of the following interfaces: The IList interface, including one-dimensional arrays. The IListSource interface, such as the DataTable and DataSet classes.


2 Answers

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);
}
like image 169
Hans Olsson Avatar answered Oct 06 '22 15:10

Hans Olsson


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

DataTable dt = new DataTable();
dt = (DataTable)dataGridView1.DataSource;
like image 35
Trenton Wallace Avatar answered Oct 06 '22 14:10

Trenton Wallace