C# Convert DataGridView to DataTable
I saw some websites which show how to bind dataTable to dataGridView.
But the opposite way was not seen.
I leave as a memorandum how to convert dataGridView to dataTable.
Code to Store DataGridView into DataTable
Here is the code.
/// Store received DataGridView into DataTable and return
/// <param name="dtgrdvwTarget">DataGridView you want to use as a table</param>
/// <param name="dtResult">Where to extract DataGridView values</param>
public DataTable retDtgrdvwValue(DataGridView dtgrdvwTarget, DataTable dtResult)
for (int row = 0; row < dtgrdvwTarget.Rows.Count - 1; row++)
DataRow drResult = dtResult.NewRow();
for (int col = 0; col < dtgrdvwTarget.Columns.Count; col++)
drResult[col] = dtgrdvwTarget.Rows[row].Cells[col].Value;
※ Not considered when NULL value is in DataGridView.
If necessary, add code to fill in “0” or “” for NULL value.
Unexpectedly, I think that it is convenient because there are times when I want to import to DataTable and update or check data extracted from DB.