Convert GridView to DataTable in C# and VB.Net

watch_later Sunday, March 31, 2019

Introduction


This article gives an explanation about how to convert GridView to DataTable in asp.net web forms with bootstrap 4 using C# and VB.Net and also show how to export a DataSource of GridView to a DataTable as well as how to how to put gridview data to datatable. Here I will also show you the optimized way to convert or export gridview to datatable in c# and vb.net and also explain how to export grid to datatable without for or foreach loop.

Convert GridView to DataTable in C# and VB.Net

In my previous articles, I explained export datatable to CSV file using c# and vb.net and how to convert JSON to datatable or dataset in asp.net web forms with bootstrap 4 using c# and vb.net and in this article, I'll show you how you can export gridview data to datatable.

Requirement 


1) Create asp.net web forms application with bootstrap 4.
2) Design a web form with two gridview one simple button.
3) Create a method that returns datatable.
4) Load first gridview on page load event using the created method that returns datatable.
5) On click of the button export/convert data source of first grid view and store in the datatable and assign that datatable to the second gid as datasource.

Implementation


Lets we start with an implementation of our requirement and first of all, we will create simple asp.net web forms application and design a web form as per our requirement and for that, you have to write following code in your ".aspx" page.

First, you have to link CSS and Javascript for Bootstrap 4 before end <head> tag.
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
Now you have to write the following code before end <body> tag, here I have used two datagridview one for display data on Page load and another for display data of the first gridview on click event of the button as per given requirement.
<div class=" container card">
            <br />
            <h2>Normal DataGridView</h2>
            <asp:GridView ID="grdFirstGridView" runat="server" CssClass="table table-bordered"></asp:GridView>
            
            <h2>Converted  DataGridView</h2>
            <asp:GridView ID="grdSecondGridView" runat="server" CssClass="table table-bordered"></asp:GridView>
            <br />
            <div>
                <asp:Button ID="btnConvert" runat="server" CssClass="btn btn-primary" Text="Convert DataGridView to Datatable" OnClick="btnConvert_Click" />
            </div>
            <br />
        </div>
Then we will create a method that returns datatable.

C# 

private DataTable GridView_DataTable()
    {
        try
        {
            DataTable dtTable = new DataTable();
            dtTable.Columns.AddRange(new DataColumn[5] { new DataColumn("RollNo"typeof(int)),
                                                    new DataColumn("StudentName"typeof(string)),
                                                    new DataColumn("Branch",typeof(string)),
                                                    new DataColumn("Semester",typeof(string)) ,
                                                    new DataColumn("University",typeof(string)) });
 
            dtTable.Rows.Add(1, "Nikunj Satasiya""Computer Science""8th""RK University");
            dtTable.Rows.Add(2, "Hiren Dobariya""Computer Science""8th""RK University");
            dtTable.Rows.Add(3, "Sarah Demola""Information Technology""8th""Oxford  University");
            dtTable.Rows.Add(4, "Vivek Ghadiya""Computer Science""4th""RK University");
            return dtTable;
        }
        catch (Exception)
        {
            throw;
        }
    }

Vb.NET

Private Function GridView_DataTable() As DataTable
        Try
            Dim dtTable As DataTable = New DataTable
            dtTable.Columns.AddRange(New DataColumn() {New DataColumn("RollNo"GetType(System.Int32)), New DataColumn("StudentName"GetType(System.String)), New DataColumn("Branch"GetType(System.String)), New DataColumn("Semester"GetType(System.String)), New DataColumn("University"GetType(System.String))})
            dtTable.Rows.Add(1, "Nikunj Satasiya""Computer Science""8th""RK University")
            dtTable.Rows.Add(2, "Hiren Dobariya""Computer Science""8th""RK University")
            dtTable.Rows.Add(3, "Sarah Demola""Information Technology""8th""Oxford  University")
            dtTable.Rows.Add(4, "Vivek Ghadiya""Computer Science""4th""RK University")
            Return dtTable
        Catch ex As Exception
            Throw
        End Try
    End Function
Now, we will bind the first gridview on page load event.

C#

protected void Page_Load(object sender, EventArgs e)
   {
       try
       {
           grdFirstGridView.DataSource = GridView_DataTable();
           grdFirstGridView.DataBind();
       }
       catch (Exception)
       {
           throw;
       }
       
   }

VB.NET

Protected Sub Page_Load(ByVal sender As ObjectByVal e As EventArgs)
        Try
            grdFirstGridView.DataSource = GridView_DataTable
            grdFirstGridView.DataBind()
        Catch  As Exception
            Throw
        End Try
 
    End Sub
Now we will Convert / Export first gridview into the datatable and assign this datatable as datasource into the second gridview.

C#

protected void btnConvert_Click(object sender, EventArgs e)
    {
        try
        {
            DataTable dt = grdFirstGridView.DataSource as DataTable;
            grdSecondGridView.DataSource = dt;
            grdSecondGridView.DataBind();
        }
        catch (Exception)
        {
            throw;
        }
    }

VB.NET

Protected Sub btnConvert_Click(ByVal sender As ObjectByVal e As EventArgs)
        Try
            Dim dt As DataTable = CType(grdFirstGridView.DataSource, DataTable)
            grdSecondGridView.DataSource = dt
            grdSecondGridView.DataBind()
        Catch  As Exception
            Throw
        End Try
 
    End Sub

Output


Load First gridview on Page Load Event

Bind Gridview on Page Load

Load Second Gridview from the first gridview on button Click.

Convert Gridview To Datatable

Summary


This article gives an explanation about how you can convert or export GridView to DataTable in asp.net web forms with bootstrap 4 using C# and VB.Net.

Codingvila provides articles and blogs on web and software development for beginners as well as free Academic projects for final year students in Asp.Net, MVC, C#, Vb.Net, SQL Server, Angular Js, Android, PHP, Java, Python, Desktop Software Application and etc.



sentiment_satisfied Emoticon