3. List Controls
List
controls display (or at least need to have in memory) many items at the
same time—specifically, the contents of the data source. Depending on
its expected behavior, the control picks the needed items from memory
and properly formats and displays them. List controls include DropDownList, CheckBoxList, RadioButtonList, ListBox, and BulletedList. All list controls inherit from the base ListControl class.
The DropDownList Control
The DropDownList
control enables users to select one item from a single-selection
drop-down list. You can specify the size of the control by setting its
height and width in pixels, but you can’t control the number of items
displayed when the list drops down. Table 1 lists the most commonly used properties of the control.
Table 1. Properties of the DropDownList Control
Property | Description |
---|
AppendDataBoundItems | Indicates whether statically defined items should be maintained or cleared when adding data-bound items. Not supported in ASP.NET 1.x. |
AutoPostBack | Indicates whether the control should automatically post back to the server when the user changes the selection. |
DataMember | The name of the table in the DataSource to bind. |
DataSource | The data source that populates the items of the list. |
DataSourceID | ID of the data source component to provide data. Not supported in ASP.NET 1.x. |
DataTextField | Name of the data source field to supply the text of list items. |
DataTextFormatString | Formatting string used to visually format list items to be displayed. |
DataValueField | Name of the data source field used to supply the value of a list item. |
Items | Gets the collection of items in the list control. |
SelectedIndex | Gets or sets the index of the selected item in the list. |
SelectedItem | Gets the selected item in the list. |
SelectedValue | Gets the value of the selected item in the list. |
The programming interface of the DropDownList also features three properties to configure the border of the drop-down list—the BorderColor, BorderStyle, and BorderWidth
properties. Although the properties are correctly transformed in
cascading style sheet (CSS) style properties, most browsers won’t use
them to change the appearance of the final drop-down list.
The DataTextField and DataValueField
properties don’t accept expressions, only plain column names. To
combine two or more fields of the data source, you can use a calculated
column. You can either use a column computed by the database or exploit
the power of the ADO.NET object model and add an in-memory column. The
following SQL query returns a column obtained by concatenating lastname and firstname:
SELECT lastname + ', ' + firstname AS 'EmployeeName' FROM Employees
The same result can also be obtained without the involvement of the database. Once you’ve filled a DataTable object with the result of the query, you add a new column to its Columns collection. The content of the column is based on an expression. The following code adds an EmployeeName column to the data source that concatenates the last name and first name:
dataTable.Columns.Add("EmployeeName",
typeof(string),
"lastname + ', ' + firstname");
An expression-based column
does not need to be filled explicitly. The values for all the cells in
the column are calculated and cached when the column is added to the
table. The table tracks any dependencies and updates the calculated
column whenever any of the constituent columns are updated.
The CheckBoxList Control
The CheckBoxList
control is a single monolithic control that groups a collection of
selectable list items with an associated check box, each of which is
rendered through an individual CheckBox
control. The properties of the child check boxes are set by reading the
associated data source. You insert a check box list in a page as
follows:
<asp:CheckBoxList runat="server" id="employeesList">
Table 2 lists the specific properties of the CheckBoxList control.
Table 2. Properties of the CheckBoxList Control
Property | Description |
---|
AppendDataBoundItems | Indicates whether statically defined items should be maintained or cleared when adding data-bound items. Not supported in ASP.NET 1.x. |
AutoPostBack | Indicates whether the control should automatically post back to the server when the user changes the selection. |
CellPadding | Indicates pixels between the border and contents of the cell. |
CellSpacing | Indicates pixels between cells. |
DataMember | The name of the table in the DataSource to bind. |
DataSource | The data source that populates the items of the list. |
DataSourceID | ID of the data source component to provide data. Not supported in ASP.NET 1.x. |
DataTextField | Name of the data source field to supply the text of list items. |
DataTextFormatString | Formatting string used to visually format list items to be displayed. |
DataValueField | Name of the data source field used to supply the value of a list item. |
Items | Gets the collection of items in the list control. |
RepeatColumns | Gets or sets the number of columns to display in the control. |
RepeatDirection | Gets or sets a value that indicates whether the control displays vertically or horizontally. |
RepeatLayout | Gets or sets the layout of the check boxes (table or flow). |
SelectedIndex | Gets or sets the index of the first selected item in the list—the one with the lowest index. |
SelectedItem | Gets the first selected item. |
SelectedValue | Gets the value of the first selected item. |
TextAlign | Gets or sets the text alignment for the check boxes. |
The CheckBoxList
does not supply any properties that know which items have been
selected. But this aspect is vital for any Web application that uses
selectable elements. The CheckBoxList can have any number of items selected, but how can you retrieve them?
Any list control has an Items property that contains the collection of the child items. The Items property is implemented through the ListItemCollection class and makes each contained item accessible via a ListItem object. The following code loops through the items stored in a CheckBoxList control and checks the Selected property of each of them:
foreach (ListItem item in chkList.Items)
{
if (item.Selected) {
// this item is selected
}
}
Figure 3
shows a sample page that lets you select some country names and
composes an ad hoc query to list all the customers from those countries.
Note that the SelectedXXX properties work in a slightly different manner for a CheckBoxList control. The SelectedIndex property indicates the lowest index of a selected item. By setting SelectedIndex
to a given value, you state that no items with a lower index should be
selected any longer. As a result, the control automatically deselects
all items with an index lower than the new value of SelectedIndex. Likewise, SelectedItem returns the first selected item, and SelectedValue returns the value of the first selected item.
The RadioButtonList Control
The RadioButtonList control acts as the parent control for a collection of radio buttons. Each of the child items is rendered through a RadioButton control. By design, a RadioButtonList can have zero or one item selected. The SelectedItem property returns the selected element as a ListItem
object. Note, though, that there is nothing to guarantee that only one
item is selected at any time. For this reason, be extremely careful
when you access the SelectedItem of a RadioButtonList control—it could be null.
if (radioButtons.SelectedValue != null)
{
// Process the selection here
...
}
The control supports the same set of properties as the CheckBoxList
control and, just like it, accepts some layout directives. In
particular, you can control the rendering process of the list with the RepeatLayout and RepeatDirection properties. By default, the list items are rendered within a table, which ensures the vertical alignment of the companion text. The property that governs the layout is RepeatLayout.
The alternative is to display the items as free HTML text, using blanks
and breaks to guarantee some sort of minimal structure. RepeatDirection is the property that controls the direction in which, with or without a tabular structure, the items flow. Feasible values are Vertical (the default) and Horizontal. RepeatColumns is the property that determines how many columns the list should have. By default, the value is 0, which means all the items will be displayed in a single row, vertical or horizontal, according to the value of RepeatDirection.
The ListBox Control
The ListBox control represents a vertical sequence of items displayed in a scrollable window. The ListBox control allows single-item or multiple-item selection and exposes its contents through the usual Items collection, as shown in the following code:
<asp:listbox runat="server" id="theListBox"
rows="5" selectionmode="Multiple" />
You can decide the height of the control through the Rows property. The height is measured in number of rows rather than pixels or percentages.
Two properties make this control slightly different than other list controls—the Rows property, which represents the number of visible rows in the control, and the SelectionMode
property, which determines whether one or multiple items can be
selected. The programming interface of the list box also contains the
set of SelectedXXX properties we considered earlier. In this case, they work as they do for the CheckBoxList control—that is, they return the selected item with the lowest index.
Note
All the list controls examined so far support the SelectedIndexChanged
event, which is raised when the selection from the list changes and the
page posts back to the server. You can use this event to execute
server-side code whenever a control is selected or deselected. |
The BulletedList Control
The BulletedList control is a programming interface built around the <ul> and <ol> HTML tags, with some extra features such as the bullet style, data binding, and support for custom images. The BulletedList control is not supported in ASP.NET 1.x. The following example uses a custom bullet object:
<asp:bulletedlist runat="server" bulletstyle="Square">
<asp:listitem>One</asp:listitem>
<asp:listitem>Two</asp:listitem>
<asp:listitem>Three</asp:listitem>
</asp:bulletedlist>
The
bullet style lets you choose the style of the element that precedes the
item. You can use numbers, squares, circles, and uppercase and
lowercase letters. The child items can be rendered as plain text,
hyperlinks, or buttons. Table 3 details the main properties of a BulletedList control.
Table 3. Properties of the BulletedList Control
Property | Description |
---|
AppendDataBoundItems | Indicates whether statically defined items should be maintained or cleared when adding data-bound items |
BulletImageUrl | Gets or sets the path to the image to use as the bullet |
BulletStyle | Determines the style of the bullet |
DataMember | The name of the table in the DataSource to bind |
DataSource | The data source that populates the items of the list |
DataSourceID | ID of the data source component to provide data |
DataTextField | Name of the data source field to supply the text of list items |
DataTextFormatString | Formatting string used to visually format list items to be displayed |
DataValueField | Name of the data source field to supply the value of a list item |
DisplayMode | Determines how to display the items: as plain text, link buttons, or hyperlinks |
FirstBulletNumber | Gets or sets the value that starts the numbering |
Items | Gets the collection of items in the list control |
Target | Indicates the target frame in the case of hyperlink mode |
The items of a BulletedList
control support a variety of graphical styles—disc, circle, custom
image, plus a few types of numberings including roman numbering. The
initial number can be programmatically set through the FirstBulletNumber property. The DisplayMode
property determines how to display the content of each bullet—plain
text (the default), link button, or hyperlink. In the case of link
buttons, the Click event is fired on
the server to let you handle the event when the page posts back. In the
case of hyperlinks, the browser displays the target page in the
specified frame—the Target property. The target URL coincides with the contents of the field specified by DataValueField.
Figure 4 shows a sample page that includes a RadioButtonList and BulletedList control. The radio-button list is bound to the contents of a system enumerated type—BulletStyle—and
displays as selectable radio buttons the various bullet styles. To bind
the contents of an enumerated type to a data-bound control, you do as
follows:
BulletOptions.DataSource = Enum.GetValues(typeof(BulletStyle));
BulletOptions.SelectedIndex = 0;
BulletOptions.DataBind();
To retrieve and set the selected value, use the following code:
BulletStyle style = (BulletStyle) Enum.Parse(typeof(BulletStyle),
BulletOptions.SelectedValue);
BulletedList1.BulletStyle = style;