
166
|
Chapter 7: Data Access and Data Binding
This is the Title of the Book, eMatter Edition
Copyright © 2008 O’Reilly & Associates, Inc. All rights reserved.
Binding to Collections
While more involved than binding to a property, binding to a collection is still
quite simple. Example 7-5 uses an ArrayList to store values that will be bound to
an ASP.NET DropDownList control. The DropDownList control and a Label
control for output are declared in the body of the page. Setting the
autopostback
attribute of the DropDownList control to True results in the page being posted
back to the server any time the selection in the dropdown is changed. In the Page_
Load event handler, if the page request is not the result of a postback, we declare
a new ArrayList and add three items to it. Next, we set the DataSource property of
the DropDownList control to be the ArrayList, call the page’s DataBind method
(which calls DataBind on its children), and then set the initial selection of the
DropDownList to the first item.
Whether or not the request is the result of a postback, we then set the output text
via the Label’s Text property and set the foreground color of the Label control
based on the value of the selected item in the dropdown. Note that because the
ForeColor property is of type System.Drawing.Color, the example uses the From-
Name method exposed by the
Color class to translate the string containing the
color ...