Binding a DataSet to a Web Forms DataGrid

367 While the child table is displayed, the corresponding row from the parent table is displayed in a header shown in Figur e 8- 5 . To return to the parent table, click the left-pointing triangle in the upper-right corner of the grid.

8.9 Binding a DataSet to a Web Forms DataGrid

Ex am ple 8- 9 shows how to bind a DataTable object to a Web Forms DataGrid object. Figur e 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_LoadByVal 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.SqlConnectionstrConnection 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.SqlDataAdapterstrSql, cn Load a data set. Dim ds As New System.Data.DataSet da.Fillds, Customers Close the database connection. cn.Close Wrap the Customers DataTable in a DataView object. Dim dv As New System.Data.DataViewds.TablesCustomers Return dv End Function GetDataSource script 368 html body asp:DataGrid id=grdCustomers runat=server ForeColor=Black AlternatingItemStyle BackColor=Gainsboro FooterStyle ForeColor=White BackColor=Silver ItemStyle BackColor=White HeaderStyle Font-Bold=True ForeColor=White BackColor=Navy asp:DataGrid body html Figure 8-6. The display generated by the code in Ex a m ple 8 - 9 Note the following: • Unlike the Windows Forms DataGrid class, the Web Forms DataGrid class has no SetDataBinding method. Instead, set the Web Forms DataGrids DataSource property and then call the DataGrids DataBind method. • Unlike the Windows Forms DataGrid class, the Web Forms DataGrid classs DataSource property cant directly consume a DataTable or DataSet. Instead, the data must be wrapped in a DataView or DataSetView object. The properties and methods of the DataView and DataSetView classes provide additional control over how data is viewed in a bound DataGrid. DataView and DataSetView objects can be used by either Windows Forms or Web Forms DataGrids, but they are mandatory with Web Forms DataGrids. • The DataGrids DataSource property can consume any object that exposes the System.Collections.ICollection interface.

8.10 Typed DataSets