How to Convert DataGridView to DataTable object? – C# Code
Here is the C# code to convert DataGridView to DataTable object for WinForm Application.
/// <summary> /// Convert DataGridView to datatable object /// </summary> /// <param name="dataGridView"></param> /// <returns>DataTable object</returns> public DataTable DataGridViewToDatatable(DataGridView dataGridView) { DataTable dt = new DataTable(); foreach (DataGridViewColumn col in dataGridView.Columns) { dt.Columns.Add(col.Name); } foreach (DataGridViewRow row in dataGridView.Rows) { DataRow dRow = dt.NewRow(); foreach (DataGridViewCell cell in row.Cells) { dRow[cell.ColumnIndex] = cell.Value; } dt.Rows.Add(dRow); } return dt; }
In the above code, I created the sampling method which takes the DataGridView object as a parameter and returns the DataTable object.