Click here to Skip to main content
15,892,537 members
Articles / Web Development / ASP.NET

Runtime Grid with Multiple DataSources

Rate me:
Please Sign up or sign in to vote.
1.33/5 (13 votes)
10 Oct 2009CPOL 30.9K   25   9
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)


Written By
Web Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 1 Pin
Dave Kreskowiak11-Oct-09 6:51
mveDave Kreskowiak11-Oct-09 6:51 
GeneralMy vote of 1 Pin
am_balaeee27-Aug-09 22:48
am_balaeee27-Aug-09 22:48 
GeneralMy vote of 1 Pin
Jürgen Bäurle2-Jan-09 11:34
Jürgen Bäurle2-Jan-09 11:34 
GeneralMy vote of 1 Pin
sprague29516-Dec-08 16:53
sprague29516-Dec-08 16:53 
GeneralMy vote of 1 Pin
MKauffman16-Dec-08 7:04
MKauffman16-Dec-08 7:04 
GeneralThe article is pretty lame. Pin
Gevorg16-Dec-08 3:08
Gevorg16-Dec-08 3:08 
GeneralMy vote of 2 Pin
AxelM15-Dec-08 20:15
AxelM15-Dec-08 20:15 
GeneralRe: My vote of 2 Pin
Jon_Boy16-Dec-08 1:42
Jon_Boy16-Dec-08 1:42 
GeneralVery Nice Pin
chandran Rama10-Sep-07 5:13
chandran Rama10-Sep-07 5:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.