DATABASE

Programming ASP.NET 3.5 : Data Source-Based Data Binding (part 3) - List Controls

10/13/2013 7:27:15 PM

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
PropertyDescription
AppendDataBoundItemsIndicates whether statically defined items should be maintained or cleared when adding data-bound items. Not supported in ASP.NET 1.x.
AutoPostBackIndicates whether the control should automatically post back to the server when the user changes the selection.
DataMemberThe name of the table in the DataSource to bind.
DataSourceThe data source that populates the items of the list.
DataSourceIDID of the data source component to provide data. Not supported in ASP.NET 1.x.
DataTextFieldName of the data source field to supply the text of list items.
DataTextFormatStringFormatting string used to visually format list items to be displayed.
DataValueFieldName of the data source field used to supply the value of a list item.
ItemsGets the collection of items in the list control.
SelectedIndexGets or sets the index of the selected item in the list.
SelectedItemGets the selected item in the list.
SelectedValueGets 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
PropertyDescription
AppendDataBoundItemsIndicates whether statically defined items should be maintained or cleared when adding data-bound items. Not supported in ASP.NET 1.x.
AutoPostBackIndicates whether the control should automatically post back to the server when the user changes the selection.
CellPaddingIndicates pixels between the border and contents of the cell.
CellSpacingIndicates pixels between cells.
DataMemberThe name of the table in the DataSource to bind.
DataSourceThe data source that populates the items of the list.
DataSourceIDID of the data source component to provide data. Not supported in ASP.NET 1.x.
DataTextFieldName of the data source field to supply the text of list items.
DataTextFormatStringFormatting string used to visually format list items to be displayed.
DataValueFieldName of the data source field used to supply the value of a list item.
ItemsGets the collection of items in the list control.
RepeatColumnsGets or sets the number of columns to display in the control.
RepeatDirectionGets or sets a value that indicates whether the control displays vertically or horizontally.
RepeatLayoutGets or sets the layout of the check boxes (table or flow).
SelectedIndexGets or sets the index of the first selected item in the list—the one with the lowest index.
SelectedItemGets the first selected item.
SelectedValueGets the value of the first selected item.
TextAlignGets 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.

Figure 3. A horizontally laid out CheckBoxList control in action.

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
PropertyDescription
AppendDataBoundItemsIndicates whether statically defined items should be maintained or cleared when adding data-bound items
BulletImageUrlGets or sets the path to the image to use as the bullet
BulletStyleDetermines the style of the bullet
DataMemberThe name of the table in the DataSource to bind
DataSourceThe data source that populates the items of the list
DataSourceIDID of the data source component to provide data
DataTextFieldName of the data source field to supply the text of list items
DataTextFormatStringFormatting string used to visually format list items to be displayed
DataValueFieldName of the data source field to supply the value of a list item
DisplayModeDetermines how to display the items: as plain text, link buttons, or hyperlinks
FirstBulletNumberGets or sets the value that starts the numbering
ItemsGets the collection of items in the list control
TargetIndicates 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();

Figure 4. A sample page to preview the style of a BulletedList control.


To retrieve and set the selected value, use the following code:

BulletStyle style = (BulletStyle) Enum.Parse(typeof(BulletStyle),
BulletOptions.SelectedValue);
BulletedList1.BulletStyle = style;
Other  
  •  SQL Server 2008 : Database mirroring overview, Mirroring modes
  •  SQL Server 2008 : Transaction log shipping - Usage scenarios, Setting up and monitoring log shipping
  •  SQL Server 2008 : High-availability options
  •  SQL Server 2008 : Policy-based management - Advanced policy-based management
  •  SQL Server 2008 : Policy-based management - Enterprise policy management
  •  SQL Server 2012 : Interpreting Query Execution Plans - Viewing Query Execution Plans
  •  SQL Server 2012 : SQL Server Management and Development Tools - Using the Query Editor
  •  SQL Server 2012 : SQL Server Management and Development Tools - Object Explorer (part 2)
  •  SQL Server 2012 : SQL Server Management and Development Tools - Object Explorer (part 1)
  •  SQL Server 2012 : SQL Server Management and Development Tools - Registered Servers
  •  SQL Server 2012 : SQL Server Management and Development Tools - Organizing the Interface
  •  SQL Server 2012 : SQL Server Private Cloud - Upgrading SQL Server
  •  SQL Server 2012 : SQL Server Private Cloud - Discovering SQL Server Sprawl
  •  SQL Server 2012 : Storage Systems (part 7) - Measuring Performance - Storage Performance Testing
  •  SQL Server 2012 : Storage Systems (part 6) - Measuring Performance - Sequential Disk Access, File Layout, Flash Storage
  •  SQL Server 2012 : Storage Systems (part 5) - Measuring Performance - Storage Performance Counters, Disk Drive Performance
  •  SQL Server 2012 : Storage Systems (part 4) - Storage Technology - Remote Data Replication, Windows Failover Clustering, SQL Server AlwaysOn Availability Groups
  •  SQL Server 2012 : Storage Systems (part 3) - Storage Technology - Storage Tiering, Data Replication
  •  SQL Server 2012 : Storage Systems (part 2) - Storage Technology - SQL Server and the Windows I/O Subsystem
  •  SQL Server 2012 : Storage Systems (part 1) - Storage Technology
  •  
    Most View
    Nikon Coolpix S6500 - 12x Optical Zoom And Integrated Wi-Fi (Part 1)
    Canon EF 24-70MM F2.8L II USM – A Standard Zoom Many Canon Users Desire
    Crucial M4 mSATA 6Gbps SSD 256GB
    Get The Most From Your Android's Browser
    Put A Padlock On Your Laptop
    Lenovo Ideapad U410 - The Powerful Ultrabook
    Understanding the Basics of Collaboration in SharePoint 2010 : Advanced List Concepts (part 1) - Large List Support, Site Columns
    Microsoft ASP.NET 3.5 : Caching Application Data (part 1) - The Cache Class
    What To Look For When Buying A New Phone Or Tablet (Part 10)
    How To Buy…A Printer (Part 2)
    Top 10
    Programming WCF Services : Security - Intranet Application Scenario (part 7) - Identity Management, Callbacks
    Programming WCF Services : Security - Intranet Application Scenario (part 6) - Authorization
    Programming WCF Services : Security - Intranet Application Scenario (part 5) - Impersonation - Impersonating all operations, Restricting impersonation
    Programming WCF Services : Security - Intranet Application Scenario (part 4) - Impersonation - Manual impersonation , Declarative impersonation
    Programming WCF Services : Security - Intranet Application Scenario (part 3) - Identities, The Security Call Context
    Programming WCF Services : Security - Intranet Application Scenario (part 2) - Constraining Message Protection, Authentication
    Programming WCF Services : Security - Intranet Application Scenario (part 1) - Securing the Intranet Bindings
    Programming WCF Services : Security - Identity Management, Overall Policy, Scenario-Driven Approach
    Programming WCF Services : Security - Transfer Security
    Programming Windows Services with Microsoft Visual Basic 2008 : Implementing the Worker Class, Creating the FileWorkerOptions Class