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.
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
:
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.
myGrid.CssClass="grid" (class name of stylesheet)
myGrid.Width = Unit.Percentage(100)