I want to get a DataTable from DataGridView of the Grid values.
In other words DataTable same as DataGridView Values
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.
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.
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);
}
You can cast the DataSource object from the DataGridView to a DataTable
DataTable dt = new DataTable();
dt = (DataTable)dataGridView1.DataSource;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With