Total Page Preview:   000000043655

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.
Abrahams
07-Dec-2019
My brother recommended Ӏ may like this blog. Ꮋe waѕ totally right. Tһis put up truly madе my ԁay. You cann't c᧐nsider jսst һow а llot time Ӏ had spent for thіs info! Ꭲhank үoᥙ!
Campa
01-Aug-2020
This paragraph will assist the internet people for setting up new blog or even a weblog from start to end.
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.
Pinkston
21-Nov-2019
I do believe all the ideas you've offered in your post. They're very convincing and can definitely work. Still, the posts are too brief for beginners. Could you please lengthen them a bit from next time? Thanks for the post.
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
Southee
22-Nov-2019
WOW just what I was looking for. Came here by searching for How to create Dynamically DataTable and bind to GridView in ASP.Net Using C# and VB.Net in Hindi
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.
Beatham
02-Aug-2020
continuously i used to read smaller posts that as well clear their motive, and that is also happening with this paragraph which I am reading here.
Paulson
22-Oct-2020
Hi mates, how is all, and what you wish for to say on the topic of this piece of writing, in my view its actually amazing in support of me.
Jeffcott
03-May-2021
I like it whenever people get together and share views. Great website, continue the good work!
Day
05-May-2021
It's awesome in favor of me to have a site, which is valuable in favor of my knowledge. thanks admin
Edmiston
10-May-2021
You need to take part in a contest for one of the most useful sites on the web. I will recommend this site!
Gloucester
13-May-2021
Hi there, just wanted to tell you, I liked this blog post. It was helpful. Keep on posting!
Ann
19-May-2021
Good article. I definitely love this site. Stick with it!
Hannah
28-Apr-2021
Do you mind if I quote a couple of your articles as long as I provide credit and sources back to your weblog? My blog site is in the very same area of interest as yours and my users would definitely benefit from a lot of the information you provide here. Please let me know if this ok with you. Thank you!
Parks
30-Apr-2021
Amazing! This blog looks exactly like my old one! It's on a totally different subject but it has pretty much the same layout and design. Great choice of colors!
Hackler
01-May-2021
Hi to all, it's truly a fastidious for me to pay a quick visit this website, it contains precious Information.
Nevarez
04-Jun-2021
I every time spent my half an hour to read this blog's articles all the time along with a mug of coffee.
Naquin
04-May-2021
Right here is the perfect web site for anyone who would like to understand this topic. You understand so much its almost tough to argue with you (not that I actually will need to…HaHa). You definitely put a fresh spin on a subject that has been written about for decades. Wonderful stuff, just excellent!
House
05-May-2021
Heya i am for the primary time here. I found this board and I to find It truly helpful & it helped me out a lot. I hope to offer one thing back and aid others such as you aided me.
Nankervis
09-May-2021
When I initially left a comment I seem to have clicked on the -Notify me when new comments are added- checkbox and now whenever a comment is added I get 4 emails with the exact same comment. Perhaps there is an easy method you can remove me from that service? Thank you!
Ireland
10-May-2021
Thank you for the good writeup. It in fact was a amusement account it. Look advanced to far added agreeable from you! By the way, how could we communicate?
Sennitt
14-May-2021
Have you ever considered writing an ebook or guest authoring on other websites? I have a blog based on the same information you discuss and would really like to have you share some stories/information. I know my subscribers would enjoy your work. If you're even remotely interested, feel free to shoot me an e mail.
Gorham
14-May-2021
Your style is so unique in comparison to other folks I have read stuff from. Thank you for posting when you've got the opportunity, Guess I will just book mark this web site.
Pratten
18-May-2021
I'm impressed, I must say. Rarely do I encounter a blog that's equally educative and amusing, and let me tell you, you have hit the nail on the head. The problem is an issue that too few men and women are speaking intelligently about. I'm very happy that I stumbled across this during my hunt for something concerning this.
Quilty
28-Apr-2021
Appreciation to my father who stated to me about this weblog, this weblog is genuinely awesome.
Theis
11-May-2021
wonderful points altogether, you simply gained a new reader. What might you recommend about your post that you simply made some days ago? Any sure?
Scotto
28-Apr-2021
I want to to thank you for this excellent read!! I absolutely loved every bit of it. I've got you saved as a favorite to look at new things you post…
Ginn
30-Apr-2021
Thanks for sharing your info. I truly appreciate your efforts and I am waiting for your further write ups thank you once again.
Meudell
28-Apr-2021
I was curious if you ever thought of changing the structure of your website? Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better. Youve got an awful lot of text for only having 1 or 2 images. Maybe you could space it out better?
McNish
30-Apr-2021
Hi, i think that i noticed you visited my website so i got here to return the want?.I'm attempting to to find things to improve my site!I suppose its ok to use a few of your ideas!!
Larose
11-May-2021
Thank you for the good writeup. It in fact was a amusement account it. Look advanced to far added agreeable from you! However, how can we communicate?
Baylor
11-May-2021
I was suggested this web site by my cousin. I'm not sure whether this post is written by him as nobody else know such detailed about my problem. You are wonderful! Thanks!
Fuchs
18-May-2021
whoah this weblog is magnificent i love studying your posts. Stay up the great work! You understand, many individuals are looking round for this information, you can aid them greatly.
Mullings
01-Jun-2021
I'm really impressed along with your writing skills and also with the structure for your blog. Is that this a paid topic or did you customize it your self? Anyway keep up the nice high quality writing, it is uncommon to peer a nice weblog like this one these days..
Burch
07-Jul-2021
I was able to find good information from your articles.

                           
                           

                           

                           

Facebook User: