Creating a DataTable and using it to populate GridView in Asp.Net with C# tutorial

DataTable is very important for handling temporary data. It allows you to hold records in memory without an actual database connection.
A GridView is used to display tabular data. In this tutorial, A DataTable is declared and some dummy data is added into it. A GridView is added into the project. Finally the GridView is used to display the dummy data in the DataTable. The tutorial is done in Asp.Net and C# as the programming language. At the end of the tutorial, sample code has been provided for download.
  1. Create a website project
  2. Drag and drop a GridView control onto the Default.aspx page
  3. Name the GridView as "grdCustomers"
  4. Open the CodeBehind page, "Default.aspx.cs" and add the following C# code, that declares a DataTable and fills it with dummy data, on Page_Load event
    ...
    if (IsPostBack == true)
        return
    DataTable dtTemp = new DataTable(); 
    dtTemp.Columns.Add("Customer ID"); 
    dtTemp.Columns.Add("First Name"); 
    dtTemp.Columns.Add("Last Name"); 
    dtTemp.Columns.Add("Address"); 
    dtTemp.Rows.Add("0001", "Peter", "Kinyanjui", "2376, 00800, Nairobi"); 
    dtTemp.Rows.Add("0002", "Alfred", "Nyasinga", "3453, 00800, Nairobi"); 
    dtTemp.Rows.Add("0003", "Alice", "Kwamboka", "6056, 00800, Nairobi"); 
    dtTemp.Rows.Add("0004", "Denis", "Nyakundi", "5672, 00800, Nairobi"); 
    dtTemp.Rows.Add("0005", "Paul", "Otieno", "8734, 00800, Nairobi"); 
    grdCustomers.DataSource = dtTemp; 
    grdCustomers.DataBind();
    ...
  5. Run the Asp.Net project

Download free code for creating DataTable and using it to populate GridView in Asp.Net with C# tutorial

Download the source files for the example here

See more tutorials on Asp.Net with C#



Date : 08 Jun 2012
Hit CountAlt