In this article I will explain with an example, how to convert
DataGridView to DataTable in
Windows Forms (WinForms) Application using C# and VB.Net.
Form Design
Namespaces
You will need to import the following namespace.
C#
VB.Net
Populating the DataGridView
Inside the
Form Load event handler, an object of
DataTable is created.
Then, three columns are added to the
DataTable Columns collection using the
AddRange method.
Inside the AddRange method, an Array of the objects of type DataColumn is specified to which, the name and the optional parameter Data Type i.e. the Type of the column is passed.
Once the schema is ready i.e. all the columns are defined and some rows have been added using the Rows.Add method.
C#
private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] {
new DataColumn("Id", typeof(int)),
new DataColumn("Name", typeof(string)),
new DataColumn("Country", typeof(string)) });
dt.Rows.Add(1, "John Hammond", "United States");
dt.Rows.Add(2, "Mudassar Khan", "India");
dt.Rows.Add(3, "Suzanne Mathews", "France");
dt.Rows.Add(4, "Robert Schidner", "Russia");
this.dataGridView1.DataSource = dt;
this.dataGridView1.AllowUserToAddRows = false;
}
VB.Net
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim dt As New DataTable()
dt.Columns.AddRange(New DataColumn() {
New DataColumn("Id", GetType(Integer)),
New DataColumn("Name", GetType(String)),
New DataColumn("Country", GetType(String))})
dt.Rows.Add(1, "John Hammond", "United States")
dt.Rows.Add(2, "Mudassar Khan", "India")
dt.Rows.Add(3, "Suzanne Mathews", "France")
dt.Rows.Add(4, "Robert Schidner", "Russia")
Me.dataGridView1.DataSource = dt
Me.dataGridView1.AllowUserToAddRows = False
End Sub
Converting DataGridView to DataTable
C#
private void btnConvert_Click(object sender, EventArgs e)
{
//Creating DataTable.
DataTable dt = new DataTable();
//Adding the Columns.
foreach (DataGridViewColumn column in dataGridView1.Columns)
{
dt.Columns.Add(column.HeaderText, column.ValueType);
}
//Adding the Rows.
foreach (DataGridViewRow row in dataGridView1.Rows)
{
dt.Rows.Add();
foreach (DataGridViewCell cell in row.Cells)
{
dt.Rows[dt.Rows.Count - 1][cell.ColumnIndex] = cell.Value.ToString();
}
}
}
VB.Net
Private Sub btnConvert_Click(sender As System.Object, e As System.EventArgs) Handles btnConvert.Click
'Creating DataTable.
Dim dt As New DataTable()
'Adding the Columns.
For Each column As DataGridViewColumn In dataGridView1.Columns
dt.Columns.Add(column.HeaderText, column.ValueType)
Next
'Adding the Rows.
For Each row As DataGridViewRow In dataGridView1.Rows
dt.Rows.Add()
For Each cell As DataGridViewCell In row.Cells
dt.Rows(dt.Rows.Count - 1)(cell.ColumnIndex) = cell.Value.ToString()
Next
Next
End Sub
Screenshot
The DataGridView
The DataTable populated from DataGridView
Downloads