As explained in the “Data Binding” section earlier in the chapter, a class that supports the ICollection interface can be treated as a data source. A server control that has a DataSource property can be bound to a collection. If you bind a DataGrid server control to the DataSet.Tables collection, as you did in Listing 5.2, you'll get a table detailing all of the properties of the DataTables in the DataSet.
Listing 5.6 shows an ASP.NET Web Form that creates a DataSet object, fills it with two DataTables, and binds it to a DataGrid, a ListBox, and a RadioButtonList.
[VB] 01: <%@ Page Language="VB" %> 02: <%@ Import Namespace="System.Data" %> 03: <%@ Import Namespace="System.Data.SqlClient" %> 04: 05: <script runat="server"> 06: Sub Page_Load(Sender As Object, E As EventArgs) 07: Dim myDataSet As New DataSet 08: Dim myDataAdapter As SqlDataAdapter 09: 10: myDataAdapter = New SqlDataAdapter("SELECT * FROM Customers", "server=localhost;database=Northwind;uid=sa;pwd=;") 11: myDataAdapter.Fill(myDataSet, "Customers") 12: 13: myDataAdapter.SelectCommand.CommandText = "SELECT * FROM Products" 14: myDataAdapter.Fill(myDataSet, "Products") 15: 16: myDataGrid.DataSource = myDataSet.Tables 17: myListBox.DataSource = myDataSet.Tables 18: myCheckboxList.DataSource = myDataSet.Tables 19: Page.DataBind() 20: End Sub 21: </script> [C#] 01: <%@ Page Language="C#" %> 02: <%@ Import Namespace="System.Data" %> 03: <%@ Import Namespace="System.Data.SqlClient" %> 04: 05: <script runat="server"> 06: void Page_Load(Object sender, EventArgs e){ 07: DataSet myDataSet = new DataSet(); 08: SqlDataAdapter myDataAdapter; 09: 10: myDataAdapter = new SqlDataAdapter("SELECT * FROM Customers", "server=localhost;database=Northwind;uid=sa;pwd=;"); 11: myDataAdapter.Fill(myDataSet, "Customers"); 12: 13: myDataAdapter.SelectCommand.CommandText = "SELECT * FROM Products"; 14: myDataAdapter.Fill(myDataSet, "Products"); 15: 16: myDataGrid.DataSource = myDataSet.Tables; 17: myListBox.DataSource = myDataSet.Tables; 18: myCheckboxList.DataSource = myDataSet.Tables; 19: Page.DataBind(); 20: } 21: </script> [VB & C#] 22: <html> 23: <head> 24: <title>Programming Datadriven Web Applications with ASP.NET - Chapter 5</title> 25: </head> 26: <body> 27: <p> 28: <b>Binding to a DataGrid</b><br> 29: <asp:DataGrid id="myDataGrid" runat="server" /> 30: </p> 31: <p> 32: <b>Binding to a ListBox</b><br> 33: <asp:ListBox id="myListBox" runat="server" /> 34: </p> 35: <p> 36: <b>Binding to a CheckboxList</b><br> 37: <asp:CheckboxList id="myCheckboxList" runat="server" /> 38: </p> 39: </body> 40: </html> |
In Listing 5.6, you create a DataSet and fill it with two DataTables, the same as you did in Listing 5.2. On lines 16–18, you set the DataSource property of three different server controls, a DataGrid, a ListBox, and a CheckboxList, to the Tables collection of the DataSet. On line 19, you call the page-level DataBind() method. Figure 5.5 shows the resulting Web page.
3.14.246.148