December 2001
Beginner
464 pages
13h 51m
English
Example 8-9 shows how to bind a DataTable object to a Web Forms DataGrid object. Figure 8-6 shows the resulting display in a web browser.
Example 8-9. Creating a DataTable and binding it to a Web Forms DataGrid
<%@ Page Explicit="True" Strict="True" %> <script language="VB" runat="server"> Protected Sub Page_Load(ByVal Sender As System.Object, _ ByVal e As System.EventArgs) If Not IsPostback Then ' True the first time the browser hits the page. ' Bind the grid to the data. grdCustomers.DataSource = GetDataSource( ) grdCustomers.DataBind( ) End If End Sub ' Page_Load Protected Function GetDataSource( ) As System.Collections.ICollection ' Open a database connection. Dim strConnection As String = _ "Data Source=localhost;Initial Catalog=Northwind;" _ & "Integrated Security=True" Dim cn As New System.Data.SqlClient.SqlConnection(strConnection) cn.Open( ) ' Set up a data adapter object. Dim strSql As String = _ "SELECT CustomerID, CompanyName, ContactName, Phone" _ & " FROM Customers" _ & " WHERE City = 'Buenos Aires' AND Country = 'Argentina'" Dim da As New System.Data.SqlClient.SqlDataAdapter(strSql, cn) ' Load a data set. Dim ds As New System.Data.DataSet( ) da.Fill(ds, "Customers") ' Close the database connection. cn.Close( ) ' Wrap the Customers DataTable in a DataView object. Dim dv As New System.Data.DataView(ds.Tables("Customers")) Return dv End Function ' GetDataSource </script> <html> <body> <asp:DataGrid id=grdCustomers runat="server" ...