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 System.Data.OleDb namespace:
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
Imports System.Linq Imports System.Web
Imports System.Web.Security Imports System.Web.UI
Imports System.Web.UI.HtmlControls Imports System.Web.UI.WebControls
Partial Public Class _Default
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
' Create a Connection object Dim ConnectionString As String = " provider = Microsoft.Jet.OLEDB.4.0; " & "Data Source=C:/Northwind.mdb"
Dim conn As New OleDbConnection(ConnectionString
' open the connection
If conn.State <> ConnectionState.Open Then
' Create a data adapter
Dim da As New OleDbDataAdapter("SELECT CustomerID,CompanyName,Address,City FROM customers", conn)
' Create and fill a dataset
Dim ds As New DataSet()
' Bind dataset to the control
DataGrid1.DataSource = ds
' Close the connection
If conn.State = ConnectionState.Open Then
conn.Close() End If
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.
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.