In this tutorial we will add data to a GridView control from multiple tables within our database using ASP.NET 4.0 and C#.

When using the gridview control there are a few different ways that we can bind data to it. Here we will walk through the steps to databind a datatable to a gridview by populating a datatable with data from multiple tabl

Adding the Default.aspx Page

First, we want to add a simple web form to the project. At this point, I have created a new ASP.NET Empty Web Site. Next, we need to do the following:

  1. Right click the project in your solution explorer.
  2. Select add new item…
  3. Select a web form.
  4. Name it ‘Default.aspx’.
  5. Click add.
  6. Open Default.aspx up to design mode.
  7. Drag and drop a gridview control onto the web form

Adding the Database

Next, we need to add a database with two tables in it that we will use to populate the gridview with data. To do this:

  1. Right click the project in your solution explorer.
  2. Select add ASP.NET folder.
  3. Select App_Data.
  4. Right click the App_Data folder in your solution explorer.
  5. Select add new item…
  6. Select a Sql Server Database.
  7. Click add.

Now that we have a database, we need to add two tables to it with some sample data. To do this:

  1. Expand the Database.mdf folder in your server/database explorer.
  2. Right click the Tables folder.
  3. Select add new table.
  4. Add the following columns with their respective types to the table:
    Column Name Data Type
    ID int
    Data nvarchar(50)
  5. Save the table as ‘Table1’.
  6. Right click the Tables folder.
  7. Select add new table.
  8. Add the following columns with their respective types to the table:
    Column Name Data Type
    ID int
    Data nvarchar(50)
  9. Save the table as ‘Table2’.

Next, we need to add some sample data to the tables. To Table1 add the following:

ID Data
1 T1 Temp data 1
2 T1 Temp data 2
3 T1 Temp data 3

To Table2 add the following:

ID Data
1 Temp data 1
2 T2 Temp data 2
3 T2 Temp data 3

Adding the ConnectionString

Now that we have a database, we need to add a new connection string to it. To do this, open up the Web.Config file for editing and add in the following code between the and tags:

Adding Data to the GridView

Next, we need to databind our data from the tables to our gridview. To do this, we need to open up Default.aspx.cs for editing and add in the following using statements:

Next, we need to add the following code to the Page_Load event method:

This code will create a datatable object, populate it with the data from both of our tables, and then databind it to our gridview.

Testing

To test this out, go ahead and load up the web site. You should see something similar to this:

Download Source Files