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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
/// <summary> /// Store received DataGridView into DataTable and return /// </summary> /// <param name="dtgrdvwTarget">DataGridView you want to use as a table</param> /// <param name="dtResult">Where to extract DataGridView values</param> /// <returns></returns> 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; } dtResult.Rows.InsertAt(drResult, row); } return dtResult; }</span> |
※ 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.