7.2 Data Binding Controls


Many server controls in ASP.NET support data binding for populating their contents. These controls expose a DataSource property to be initialized to any object that supports the IEnumerable interface, as well as DataTables and DataSets . When the control's DataBind() method is invoked, the collection is traversed, and the contents of the control are filled with whatever was in the collection. Like the Render method of controls, the DataBind method invokes DataBind on any of the control's child controls. So invoking the Page 's top-level DataBind() method implicitly invokes all the DataBind() methods for all controls on that page. Alternatively, you can elect to invoke each control's DataBind() method independently. Figure 7-2 shows a list of all the controls that support data binding, and some of the most common classes that support IEnumerable and are thus suitable for attaching to a data-bound control.

Figure 7-2. Controls Capable of Data Binding, and Some Common Collections to Bind To

graphics/07fig02.gif

Note that the list of data sources includes many collection classes in addition to the ADO.NET classes. This means that binding data to a control does not necessarily mean that you are retrieving data from a database; it could just as well mean that you have manually populated an array of values that you want displayed in a list box. Listing 7-2 shows a page that binds a hand- constructed ArrayList to a number of server controls, and Figure 7-3 shows an instance of this page running.

Listing 7-2 Binding an ArrayList to Several Server Controls
 <! File: ArrayListBind.aspx > <%@ Page Language="C#" %> <html> <body> <head> <script runat=server>   void Page_Load(Object sender, EventArgs e)   {     if (!Page.IsPostBack) {       ArrayList vals = new ArrayList();       vals.Add("v1");       vals.Add("v2");       vals.Add("v3");       vals.Add("v4");       s1.DataSource  = vals;       cbl1.DataSource= vals;       dd1.DataSource = vals;       lb1.DataSource = vals;       rbl1.DataSource= vals;       DataBind();     }  } </script> </head> <form runat=server>   <Select id="s1" runat=server /> <br/>   <asp:CheckBoxList id="cbl1" runat=server /> <br/>   <asp:DropDownList id="dd1" runat=server /> <br/>   <asp:ListBox id="lb1" runat=server /> <br/>   <asp:RadioButtonList id="rbl1" runat=server /> <br/> </form> </body> </html> 
Figure 7-3. ArrayListBind.aspx Page Instance

graphics/07fig03.gif



Essential ASP.NET With Examples in C#
Essential ASP.NET With Examples in C#
ISBN: 0201760401
EAN: 2147483647
Year: 2003
Pages: 94
Authors: Fritz Onion

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