How to Convert DataGridView to DataTable object? – C# Code

5
(2)

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.

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 2

No votes so far! Be the first to rate this post.

As you found this post useful...

Share this post on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?