Load Data into GridView in ASP.Net

December 19, 2012 // In: C#

A GridView is a graphical user interface element that presents a tabular view of data. In this tutorial I’ll show you, how to load Data in to gridview in ASP.Net using C# (C-Sharp).

Load Records into GridView is pretty simple and easy. What you have to do is to load record from the database, List or through any data source and set it to GridView data source. In this tutorial I’ll load records from List.

Load Data into GridView

What you need is to place a GridView and a Button on the Web Page.

Create Class to make a List of  Data

Go to Project menu and click on Add Class or use shortcut keys SHIFT + ALT + C to add a new class.

Save that class file with the name Customer.cs. Here is the code for Customer class.

Don’t Understand this? Don’t worry, Its nothing but getter and setter properties to create Customers List.

Create function to load List with Some Data

On the Web Pag’s Code window, add Generate_Data function, which loads some data into List of Customers and at the end return that  List to Bind with GridView.

 Bind GridView

Now, the final step is what you actually want to do, Binding GridView. To Show something in the GridView you need to Bind the GridView with some Data Source. In this tutorial, Data Source is List of Customers (List<Customer>). You need to set GridView’s Property DataSource. After assigning DataSource we Bind that DataSource with the GridView by Calling GridView’s method DataBind().

Go to Design View of the Web Page double click on the Button that you created earlier and place the following code there.

And you have done.

What you did in your final step? Its pretty simple. Just created an object of List of Customers lstCustomer, load the dummy data that you’re to show in the gridview in the lstCustomer through Generate_Data(), Finally we set the DataSource of the GridView to the lstCustomer and Bind the Data of the GridView by Calling GridView’s DataBind Method.

I’ve also uploaded sample code used in this tutorial. Feel free to download and ask question in the comment section.

Download GridView Sample

Download Try it today for free!

Run Application in Administrator Mode in VS2010
Calculate md5 Hash in C#