Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Runtime Grid with Multiple DataSources

1.33/5 (13 votes)
10 Oct 2009CPOL 1  
This article describes how to create a DataGrid at runtime according to the tables available in the DataSet.

Introduction

This article shows how to create a runtime DataGrid using code-behind (C# or VB.NET).

Background

The PlaceHolder web server control enables you to place an empty container control within the page and then dynamically add, remove, or loop through child elements at run time. The control only renders its child elements; it has no HTML-based output of its own.

Using the code

Step 1

Create a data source first for the DataGrid to be displayed. Fill the DataSet using SqlDataAdapter. For now, we can bind two tables from the database 'Pubs'. Place a PlaceHolder in the ASPX page.

VB
Dim sql as String ="select * from authors select * from publishers"
Dim da As SqlDataAdapter = New SqlDataAdapter(sql, conn)
da.Fill(ds)

Now the DataSet contains two tables which we have to bind to a grid in a single page.

Step 2

Write the following code after filling the DataSet:

VB
Dim myGrid As DataGrid
Dim dt As DataTable

For Each dt In ds.Tables
    myGrid = New DataGrid
    myGrid.DataSource = dt
    myGrid.DataBind()
    PlaceHolder1.Controls.Add(myGrid)
Next

There is no need to create a design code when another table is bound to the DataSet.

We can also set the runtime properties of the DataGrid such as CSSClass, etc.

VB
myGrid.CssClass="grid" (class name of stylesheet)
myGrid.Width = Unit.Percentage(100)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)