Total Page Preview:   000000028451

Create Dynamically DataTable and bind to GridView in ASP.Net Using C# and VB.Net

 

In this article we will create dynamically datatable in a web application in C#, vb.net. Instead of a database table we will create a table in a code behind file using the DataTable class.

 

We will create one web page:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

     <title></title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:GridView ID="gvEmployee" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None">

            <AlternatingRowStyle BackColor="White" />

            <EditRowStyle BackColor="#2461BF" />

            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />

            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />

            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />

            <RowStyle BackColor="#EFF3FB" />

            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />

            <SortedAscendingCellStyle BackColor="#F5F7FB" />

            <SortedAscendingHeaderStyle BackColor="#6D95E1" />

            <SortedDescendingCellStyle BackColor="#E9EBEF" />

            <SortedDescendingHeaderStyle BackColor="#4870BE" />

       </asp:GridView>

    </div>

    </form>

</body>

</html>

 

 

 

Namespaces

You will need to import the following namespace.

C#

using System.Data;

 

VB.NET

Imports System.Data

 

Dynamically create DataTable and bind to GridView in ASP.Net

In the Page Load event of the page I am first creating a new instance of DataTable. Then I am adding three columns to the DataTable Columns collection using the AddRange method of the DataTable.

The AddRange method is a nice way to replace the traditional way of adding one column at a time using the Add method. In the AddRange method we need to pass an Array of the objects of type DataColumn.

And we need to specify the name and the optional parameter Data Type i.e. the Type of data the column will hold.

Once the schema is ready i.e. all the columns are defined, we can now add rows to the dynamically generated DataTable and bind it to the ASP.Net GridView control.

 

C# code

protected void Page_Load(object sender, EventArgs e)

{

       BindGridviewData();

}

 /// <summary>

 /// Dynamically create & bind data to datatable and bind datatable to gridview

/// </summary>

protected void BindGridviewData()

{

            DataTable dtEmp = new DataTable();

           dtEmp.Columns.Add("EmpId", typeof(Int32));

            dtEmp.Columns.Add("EmployeeName", typeof(string));

            dtEmp.Columns.Add("MobileNo", typeof(string));

            dtEmp.Columns.Add("EmailId", typeof(string));

            dtEmp.Columns.Add("Address", typeof(string));

 

            DataRow dtrow = dtEmp.NewRow();     // Create New Row

            dtrow["EmpId"] = 1;                 //Bind Data to Columns

            dtrow["EmployeeName"] = "Brijesh Kumar";

            dtrow["MobileNo"] = "9721621522";

            dtrow["EmailId"] = "sannykumar250@gmail.com";

            dtrow["Address"] = "Delhi";

            dtEmp.Rows.Add(dtrow);

 

            dtrow = dtEmp.NewRow();               // Create New Row

            dtrow["EmpId"] = 2;                 //Bind Data to Columns

            dtrow["EmployeeName"] = "Dilip Kumar";

            dtrow["MobileNo"] = "9721621522";

            dtrow["EmailId"] = "dilip@gmail.com";

            dtrow["Address"] = "Noida";

            dtEmp.Rows.Add(dtrow);

 

 

            dtrow = dtEmp.NewRow();              // Create New Row

            dtrow["EmpId"] = 3;                          //Bind Data to Columns

            dtrow["EmployeeName"] = "Vipul Batt";

            dtrow["MobileNo"] = "9721621522";

            dtrow["EmailId"] = "vipul@gmail.com";

            dtrow["Address"] = "Lucknow";

            dtEmp.Rows.Add(dtrow);

 

            dtrow = dtEmp.NewRow();              // Create New Row

            dtrow["EmpId"] = 1;                 //Bind Data to Columns

            dtrow["EmployeeName"] = "Ashutosh Mishra";

            dtrow["MobileNo"] = "9721621522";

            dtrow["EmailId"] = "ashutosh@gmail.com";

            dtrow["Address"] = "Patna";

            dtEmp.Rows.Add(dtrow);

 

            //Gridview will bind

            gvEmployee.DataSource = dtEmp;

            gvEmployee.DataBind();

  }

 

 

In VB Code :

  Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load

 

        If Not IsPostBack Then

            BindGridviewData()

        End If

    End Sub

    ' Dynamically create & bind data to datatable and bind datatable to gridview

    Protected Sub BindGridviewData()

        Dim dtEmp As New DataTable()

        dtEmp.Columns.Add("EmpId", GetType(Int32))

        dtEmp.Columns.Add("EmployeeName", GetType(String))

        dtEmp.Columns.Add("MobileNo", GetType(String))

        dtEmp.Columns.Add("EmailId", GetType(String))

        dtEmp.Columns.Add("Address", GetType(String))

 

 

        Dim dtrow As DataRow = dtEmp.NewRow()

        ' Create New Row

        dtrow("EmpId") = 1

        dtrow("EmployeeName") = "Brijesh Kumar"

        dtrow("MobileNo") = "9721621522"

        dtrow("EmailId") = "sannykumar250@gmail.com"

        dtrow("Address") = "Delhi"

        dtEmp.Rows.Add(dtrow)

 

        dtrow = dtEmp.NewRow()

        ' Create New Row

        dtrow("EmpId") = 2

        dtrow("EmployeeName") = "Dilip Kumar"

        dtrow("MobileNo") = "9721621522"

        dtrow("EmailId") = "dilip@gmail.com"

        dtrow("Address") = "Noida"

        dtEmp.Rows.Add(dtrow)

 

 

        gvEmployee.DataSource = dtEmp

        gvEmployee.DataBind()

    End Sub

 

 

OUTPUT:

Create Dynamically DataTable and bind to GridView in ASP.Net Using C# and VB.Net

 

 

Thank You

About Author

Brijesh Kumar

Database Developer

I have more then 6 years Experience in Microsoft Technologies - SQL Server Database, ETL Azure Cloud - Azure SQL Database, CosmosDB, Azure Data Factory, PowerBI, Web Job, Azure Function, Azure Storage, Web Apps, Powershall and Database Migration On-Premise to Azure Cloud.
LinkedIn : https://www.linkedin.com



Comments

SANNY KUMAR
18-Mar-2016
This article is very simple and helpful.
Cortez
04-Jul-2019
Thank you for the auspicious writeup. It in fact was a amusement account it. Look advanced to far added agreeable from you! By the way, how can we communicate?
Sana
10-Nov-2016
This is beneficial for us Thanks
Stutchbury
10-Jun-2017
This is a smart and very cost effective way to shop for all your handbag needs. In this type of business the dropshipper or the wholesaler supplier will be the one who will provide the products to you and delivers to the customers. If you are not savvy with web design or computer programming, this could be a very wise move.
Borella
10-Jun-2017
This is really interesting, You're a very skilled blogger. I've joined your feed and look forward to seeking more of your great post. Also, I've shared your web site in my social networks!
Skidmore
10-Jul-2019
I'm not sure where you are getting your information, but good topic. I needs to spend some time learning much more or understanding more. Thanks for wonderful info I was looking for this info for my mission.
Keating
12-Nov-2019
Hi, I do believe this is an excellent site. I stumbledupon it ; ) I'm going to return once again since i have book marked it. Money and freedom is the greatest way to change, may you be rich and continue to help other people.
Hammons
07-Oct-2019
Great blog here! Also yyour website loads uup fast! What web host are you using? Can I get your affiliate link tto your host? I wish my site loaded up as fast as yours lol
Staton
16-Nov-2019
Link exchange is nothing else but it is simply placing the other person's blog link on your page at suitable place and other person will also do similar in favor of you.

                           
                           

                           

                           

Facebook User: