Binding to Arrays

only for RuBoard

Just as you can bind a server control to a DataTable , you can also bind a server control to an array. The concept is the same. The DataBind() method works for any data source. Listing 5.5 shows an ASP.NET Web Form that creates an ArrayList object and binds it to a DataGrid , a DropDownList , and a RadioButtonList .

Listing 5.5 Binding Server Controls to an ArrayList
 [VB] 01: <%@ Page Language="VB" %> 02: 03: <script runat="server"> 04:   Sub Page_Load(Source As Object, E As EventArgs) 05:     Dim al As New ArrayList 06:     al.Add("Item 1") 07:     al.Add("Item 2") 08:     al.Add("Item 3") 09:     al.Add("Item 4") 10:     al.Add("Item 5") 11:     myDataGrid.DataSource = al 12:     myDropDownList.DataSource = al 13:     myRadioButtonList.DataSource = al 14:     Page.DataBind() 15:   End Sub 16: </script> [C#] 01: <%@ Page Language="C#" %> 02: 03: <script runat="server"> 04:   void Page_Load(Object sender, EventArgs e){ 05:     ArrayList al = new ArrayList(); 06:     al.Add("Item 1"); 07:     al.Add("Item 2"); 08:     al.Add("Item 3"); 09:     al.Add("Item 4"); 10:     al.Add("Item 5"); 11:     myDataGrid.DataSource = al; 12:     myDropDownList.DataSource = al; 13:     myRadioButtonList.DataSource = al; 14:     Page.DataBind(); 15:   } 16: </script> [VB & C#] 17: <html> 18: <head> 19: <title>Programming Datadriven Web Applications with ASP.NET - Chapter 5</title> 20: </head> 21: <body> 22:   <p> 23:     <b>Binding to a DataGrid</b><br> 24:     <asp:DataGrid id="myDataGrid" runat="server" /> 25:   </p> 26:   <p> 27:     <b>Binding to a DropDownList</b><br> 28:     <asp:DropDownList id="myDropDownList" runat="server" /> 29:   </p> 30:   <p> 31:     <b>Binding to a RadioButtonList</b><br> 32:     <asp:RadioButtonList id="myRadioButtonList" runat="server" /> 33:   </p> 34: </body> 35: </html> 

In Listing 5.5, you create an ArrayList on line 5. On Lines 6 “10, you add some items to the ArrayList using the Add() method of the ArrayList class. Just as in previous examples, on lines 11 “13, you set the DataSource property of each of the server controls. You use the ArrayList as the data source. Lastly, on line 14, you use the Page.DataBind() method to bind all of the controls in the Web Form to their data source. Figure 5.4 shows the rendered Web page created in Listing 5.5.

Figure 5.4. An ArrayList can be bound to any server control that has a DataSource property.
graphics/05fig04.gif
only for RuBoard


Programming Data-Driven Web Applications with ASP. NET
Programming Data-Driven Web Applications with ASP.NET
ISBN: 0672321068
EAN: 2147483647
Year: 2000
Pages: 170

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net