This article has been
excerpted from book "A Programmer's Guide to ADO.NET in C#".
The DataGrid control is a useful control in Web Forms. In this example I'll show
you how to connect a DataGrid control a database table and view all the table's
data in the DataGrid.
First you create a Web application using the same steps you've used in two
previous samples. Then you drag a button and data grid control onto the page.
Change the Text property of the button to "Fill Data," change its properties,
and add some to the page. The final Web page look like figure 7-18
Figure 7-18. Database application in ASP.NET
The only thing you need to do now is write code to fill the data from a data
base to the list box on the Fill Data button-click event handler. I'll use the
OleDb data provider with the Access 2000 NorthWind database. Before using the
OleDb data provider, though, don't forget to add a reference to the
Now write a click event handler for the button and write the code from Listing
7-3 on the handler.
Listing 7-3. Filling data from a database to the DataGrid
public partial class _Default
// Create a
string ConnectionString =
@" provider = Microsoft.Jet.OLEDB.4.0; " +
OleDbConnection conn =
// open the
if (conn.State !=
// Create a data
OleDbDataAdapter da =
CustomerID,CompanyName,Address,City FROM customers", conn);
// Create and fill a
DataSet ds =
// Bind dataset to
DataGrid1.DataSource = ds;
// Close the
if (conn.State ==
As you can see from Listing7-3, there is nothing new except one line:
DataGrid.DataBind(). I'll discuss the DataBind method in a moment. You'll follow
the same steps to create a connection and data adapter objects as you've been
doing in the previous articles of the site. In this example, I'm using The
Access 2000 database, C:\\Northwind.mdb, and the OleDb data adapter to connect
to the database. After creating a connection and data adapter, create and fill a
dataset by calling to the data adapter's Fill method. After that, set dataset as
the DataGrid control's Data Source property and call DataGrid's DataBind method.
Now Compile and run the project. The output of the Fill Data button looks like
Figure 7-19. The output of clicking the Fill Data button
Neat, huh? How easy are writing database Web applications using ADO.NET?
Hope this article would have helped you in understanding Viewing Data in a
DataGrid Control in ADO.NET. See other articles on
the website also for further reference.
| ||This essential guide
to Microsoft's ADO.NET overviews C#, then leads you toward deeper
understanding of ADO.NET. |