The List controls enable you to display simple lists of options. For example, you can use the RadioButtonList
control to display a group of radio buttons, or the BulletedList
control to display a list of links.
In this chapter, you learn how to use each of the List controls included in the ASP.NET Framework. In particular, it discusses the DropDownList
, RadioButtonList
, ListBox
, CheckBoxList
, and BulletedList
controls. You learn how to bind the different types of List controls to a data source such as a database table. You also learn how to work directly with the list items contained by a List control.
Finally, at the end of this chapter, you learn how to build a custom List control. We create a client-side multi-select List control that enables you to select multiple list items at a time.
All five of the List controls inherit from the base ListControl
class. This means that all the List controls share a common set of properties and methods. In this section, you are provided with an overview of the common features of the List controls.
The List controls render a list of options. Each option is represented by an instance of the ListItem
class. For example, you can use the page in Listing 10.1 to render a set of options for selecting your favorite movie (see Figure 10.1).
Example 10.1. FavoriteMovie.aspx
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Favorite Movie</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label id="lblMovies" Text="Favorite Movie:" AssociatedControlID="rblMovies" Runat="server" /> <asp:RadioButtonList id="rblMovies" Runat="server"> <asp:ListItem Text="The Remains of the Day" Value="movie1" /> <asp:ListItem Text="Star Wars" Value="movie2" /> <asp:ListItem Text="Pulp Fiction" Value="movie3" /> </asp:RadioButtonList> </div> </form> </body> </html>
The page in Listing 10.1 contains a RadioButtonList
control. This control contains three ListItem
controls that correspond to the three radio buttons. All the List controls use the ListItem
control to represent individual list items.
The ListItem
control supports the following five properties:
Attributes
—. Enables you to add HTML attributes to a list item.
Enabled
—. Enables you to disable a list item.
Selected
—. Enables you to mark a list item as selected.
Text
—. Enables you to specify the text displayed by the list item.
Value
—. Enables you to specify a hidden value associated with the list item.
You use the Text
property to indicate the text that you want the option to display, and the Value
property to indicate a hidden value associated with the option. For example, the hidden value might represent the value of a primary key column in a database table.
The Selected
property enables you to show a list item as selected. Selected radio buttons and check boxes appear checked. The selected option in a DropDownList
is the default option displayed. Selected options in a ListBox
appear highlighted. And, in the case of a BulletedList
control, the selected
property has no effect whatsoever.
The Enabled
property has different effects when used with different List controls. When you set a ListItem
control’s Enabled
property to the value False
when using the DropDownList
or ListBox
controls, the list item is not rendered to the browser. When you use this property with a CheckBoxList
, RadioButtonList
, or BulletedList
control, then the list item is ghosted and non-functional.
You can bind any of the List controls to a data source. The List controls support both declarative databinding and programmatic databinding.
For example, the page in Listing 10.2 contains a DropDownList
control that is bound to the Movies database table with declarative databinding (see Figure 10.2).
Example 10.2. DeclarativeDataBinding.aspx
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Declarative DataBinding</title> </head> <body> <form id="form1" runat="server"> <div> <asp:DropDownList id="ddlMovies" DataSourceID="srcMovies" DataTextField="Title" DataValueField="Id" Runat="server" /> <asp:SqlDataSource id="srcMovies" SelectCommand="SELECT Id, Title FROM Movies" ConnectionString="<%$ ConnectionStrings:Movies %>" Runat="server" /> </div> </form> </body> </html>
Notice that the DropDownList
control’s DataSourceID
property points to the ID of the SqlDataSource
control. When you open the page in Listing 10.2, the SqlDataSource
control retrieves the records from the Movies database table. The DropDownList
control grabs these records from the SqlDataSource
control and creates a ListItem
control for each data item.
You also should notice that the DropDownList
control has both its DataTextField
and DataValueField
properties set. When the DropDownList
control creates each of its list items, it uses the values of the DataTextField
and DataValueField
properties to set the Text
and Value
properties of each list item.
As an alternative to declarative databinding, you can programmatically bind any of the List controls to a data source. For example, the page in Listing 10.3 binds a ListBox
control to a collection which represents a shopping cart (see Figure 10.3).
Example 10.3. ProgrammaticDataBinding.aspx
<%@ Page Language="C#" %> <%@ Import Namespace="System.Collections.Generic" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <script runat="server"> /// <summary> /// Represents an item in the /// shopping cart /// </summary> public class CartItem { private int _id; public string _description; public int Id { get { return _id; } } public string Description { get { return _description; } } public CartItem(int id, string description) { _id = id; _description = description; } } void Page_Load() { if (!IsPostBack) { // Create shopping cart List<CartItem> shoppingCart = new List<CartItem>(); shoppingCart.Add(new CartItem(1, "Notebook Computer")); shoppingCart.Add(new CartItem(2, "HD Plasma Television")); shoppingCart.Add(new CartItem(3, "Lava Lamp")); // Bind ListBox to shopping cart lstShoppingCart.DataSource = shoppingCart; lstShoppingCart.DataBind(); } } </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Programmatic DataBinding</title> </head> <body> <form id="form1" runat="server"> <div> <asp:ListBox id="lstShoppingCart" DataTextField="Description" DataValueField="Id" Runat="server" /> </div> </form> </body> </html>
In Listing 10.3, the ListBox
is bound to the collection in the Page_Load()
method. Notice that the DataTextField
and DataValueField
properties of the ListBox
control represent properties of the CartItem
class.
Displaying options with the List controls is all very nice, but at some point you need to be able to determine which option a user has selected. The List controls support three properties that you can use to determine the selected list item:
SelectedIndex
—. Gets or sets the index of the selected list item.
SelectedItem
—. Gets the first selected list item.
SelectedValue
—. Gets or sets the value of the first selected list item.
For example, the page in Listing 10.4 enables you to select an item from the DropDownList
control and display the value of the selected item’s Text
property (see Figure 10.4).
Example 10.4. SelectMovie.aspx
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <script runat="server"> protected void btnSelect_Click(object sender, EventArgs e) { lblSelectedMovie.Text = ddlMovies.SelectedItem.Text; } </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Select Movie</title> </head> <body> <form id="form1" runat="server"> <div> <asp:DropDownList id="ddlMovies" DataSourceID="srcMovies" DataTextField="Title" DataValueField="Id" Runat="server" /> <asp:Button id="btnSelect" Text="Select" OnClick="btnSelect_Click" Runat="server" /> <hr /> <asp:Label id="lblSelectedMovie" Runat="server" /> <asp:SqlDataSource id="srcMovies" SelectCommand="SELECT Id, Title FROM Movies" ConnectionString="<%$ ConnectionStrings:Movies %>" Runat="server" /> </div> </form> </body> </html>
The SelectedItem
property is used to retrieve the selected ListItem
control from the DropDownList
control. The value of the selected item’s Text
property is displayed in the Label
control.
You can use these properties when you want to associate a List control with another DataBound
control. For example, the page in Listing 10.5 contains a DropDownList
control that displays a list of movie categories and a GridView
control that displays a list of movies that match the selected category (see Figure 10.5).
Example 10.5. ShowMoviesByCategory.aspx
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <style type="text/css"> .gridView { margin-top:20px; } .gridView td, .gridView th { padding:10px; } </style> <title>Show Movies by Category</title> </head> <body> <form id="form1" runat="server"> <div> <asp:DropDownList id="ddlMovieCategory" DataSourceID="srcMovieCategories" DataTextField="Name" DataValueField="Id" Runat="server" /> <asp:Button id="btnSelect" Text="Select" Runat="server" /> <asp:GridView id="grdMovies" DataSourceID="srcMovies" CssClass="gridView" Runat="server" /> <asp:SqlDataSource id="srcMovieCategories" SelectCommand="SELECT Id, Name FROM MovieCategories" ConnectionString="<%$ ConnectionStrings:Movies %>" Runat="server" /> <asp:SqlDataSource id="srcMovies" SelectCommand="SELECT Title,Director FROM Movies WHERE CategoryId=@Id" ConnectionString="<%$ ConnectionStrings:Movies %>" Runat="server"> <SelectParameters> <asp:ControlParameter Name="Id" ControlID="ddlMovieCategory" PropertyName="SelectedValue" /> </SelectParameters> </asp:SqlDataSource> </div> </form> </body> </html>
The DropDownList
control is bound to the srcMovieCategories SqlDataSource
control, and the GridView
control is bound to the srcMovies SqlDataSource
control. The srcMovies SqlDataSource
control includes a ControlParameter
, which represents the SelectedValue
property of the DropDownList
control. When you select a movie category from the DropDownList
control, the selected value changes and the GridView
control displays a list of matching movies.
You can mix the list items that you declare in a List control and the list items that are added to the control when it is bound to a data source. This is useful when you want to display a default selection.
For example, imagine that you are creating a form in which you want to require a user to pick an item from a List control. In this situation, you should add a default item to the List control so you can detect whether a user has actually picked an item.
You can mix declarative list items with databound list items by assigning the value True
to the AppendDataBoundItems
property. The page in Listing 10.6 illustrates how you can add a default list item to a List control (see Figure 10.6).
Example 10.6. AppendListItems.aspx
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Append List Items</title> </head> <body> <form id="form1" runat="server"> <div> <asp:DropDownList id="ddlMovies" DataSourceID="srcMovies" DataTextField="Title" DataValueField="Id" AppendDataBoundItems="True" Runat="server"> <asp:ListItem Text="Select a Movie" Value="" /> </asp:DropDownList> <asp:RequiredFieldValidator id="valMovies" Text="(Required)" ControlToValidate="ddlMovies" Runat="server" /> <br /><br /> <asp:Button id="btnSubmit" Text="Submit Form" Runat="server" /> <asp:SqlDataSource id="srcMovies" SelectCommand="SELECT Id, Title FROM Movies" ConnectionString="<%$ ConnectionStrings:Movies %>" Runat="server" /> </div> </form> </body> </html>
The page in Listing 10.6 includes both a DropDownList
control and a RequiredFieldValidator
control. The DropDownList
control includes a list item that displays the text “Select a Movie.” The Value
property of this list item is set to the empty string. If you attempt to submit the form without selecting a list item other than the default list item, then the RequiredFieldValidator
displays an error message.
Notice that the DropDownList
control includes an AppendDataBoundItems
property that is set to the value True
. If you neglect to set this property, then the databound list items overwrite any declarative list items.
All the List controls, except for the BulletedList
control, support a property named the AutoPostBack
property. When this property is assigned the value True
, the form containing the List control is automatically posted back to the server whenever a new selection is made.
For example, the page in Listing 10.7 contains a DropDownList
control that has its AutoPostBack
property enabled. When you select a new item from the DropDownList
control, the page is automatically posted back to the server and the Label control displays the selected item.
Example 10.7. AutoPostBackListControl.aspx
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <script runat="server"> protected void ddlMovies_SelectedIndexChanged(object sender, EventArgs e) { lblSelectedMovie.Text = ddlMovies.SelectedItem.Text; } </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>AutoPostBack List Control</title> </head> <body> <form id="form1" runat="server"> <div> <asp:DropDownList id="ddlMovies" DataSourceID="srcMovies" DataTextField="Title" DataValueField="Id" AutoPostBack="true" OnSelectedIndexChanged="ddlMovies_SelectedIndexChanged" Runat="server" /> <br /><br /> <asp:Label id="lblSelectedMovie" Runat="server" /> <asp:SqlDataSource id="srcMovies" SelectCommand="SELECT Id, Title FROM Movies" ConnectionString="<%$ ConnectionStrings:Movies %>" Runat="server" /> </div> </form> </body> </html>
When you enable the AutoPostBack
property, a JavaScript onchange()
event handler is added to the List control. The onchange
event is supported by all recent browsers including Firefox 1.0 and Opera 8.0.
Notice that the DropDownList
control has a SelectedIndexChanged
event handler named ddlMovies_SelectedIndexChanged()
. The SelectedIndexChanged
event is raised whenever you make a new selection in the List control (independent of the AutoPostBack
property). The ddlMovies_SelectedIndexChanged()
method displays the selected list item in a Label control.
You should avoid using the AutoPostBack
property because it creates accessibility problems for persons with disabilities. If you can’t use a mouse, and you are interacting with a website through the keyboard, having a page post back to the server whenever you make a selection change is a very frustrating experience.
All the list items rendered by a List control are contained in the List control’s list item collection. This collection is exposed by the Items
property.
You can work directly with the list items in this collection. For example, you can add or remove particular list items or you can change the order of the list items.
The page in Listing 10.8 contains two ListBox
controls and two button controls. When you click the Add button, a list item is moved from the first ListBox
to the second ListBox
control. When you click Remove, the list item is moved back to the original List control (see Figure 10.7).
Example 10.8. ListPicker.aspx
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <script runat="server"> /// <summary> /// Move item from All Movies to Favorite Movies /// </summary> protected void btnAdd_Click(object sender, EventArgs e) { ListItem item = lstAllMovies.SelectedItem; if (item != null) { lstAllMovies.Items.Remove(item); lstFavoriteMovies.ClearSelection(); lstFavoriteMovies.Items.Add(item); } } /// <summary> /// Move item from Favorite Movies to All Movies /// </summary> protected void btnRemove_Click(object sender, EventArgs e) { ListItem item = lstFavoriteMovies.SelectedItem; if (item != null) { lstFavoriteMovies.Items.Remove(item); lstAllMovies.ClearSelection(); lstAllMovies.Items.Add(item); } } /// <summary> /// When the form is submitted, /// show the contents of the /// Favorite Movies ListBox /// </summary> protected void btnSubmit_Click(object sender, EventArgs e) { foreach (ListItem item in lstFavoriteMovies.Items) lblResults.Text += "<li>" + item.Text; } </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <style type="text/css"> .listPicker { border:solid 1px black; padding:5px; width:380px; background-color:silver; } .listPicker select { width:100%; } </style> <title>List Picker</title> </head> <body> <form id="form1" runat="server"> <div class="listPicker"> <div style="float:left;width:40%"> <asp:ListBox id="lstAllMovies" DataSourceID="srcMovies" DataTextField="Title" DataValueField="Id" Runat="server" /> </div> <div style="float:left;width:20%;text-align:center"> <asp:Button id="btnAdd" Text="—>" ToolTip="Add List Item" Runat="server" OnClick="btnAdd_Click" /> <br /> <asp:Button id="btnRemove" Text="<—" ToolTip="Remove List Item" Runat="server" OnClick="btnRemove_Click" /> </div> <div style="float:left;width:40%"> <asp:ListBox id="lstFavoriteMovies" Runat="server" /> </div> <br style="clear:both" /> </div> <p> <asp:Button id="btnSubmit" Text="Submit Form" Runat="server" OnClick="btnSubmit_Click" /> </p> <hr /> <asp:Label id="lblResults" EnableViewState="false" Runat="server" /> <asp:SqlDataSource id="srcMovies" SelectCommand="SELECT Id, Title FROM Movies" ConnectionString="<%$ ConnectionStrings:Movies %>" Runat="server" /> </form> </body> </html>
The first ListBox
in Listing 10.8 is bound to the Movies database table. You can use the ListBox
controls to pick your favorite movies by moving movie titles from the first ListBox
to the second ListBox
.
When you click the Add button, the btnAdd_Click()
method executes. This method grabs the selected item from the All Movies ListBox and adds it to the Favorite Movies ListBox. The Remove button does exactly the opposite.
Notice that both the btnAdd_Click()
and btnRemove_Click()
methods call the ClearSelection()
method of the ListBox
class. This method iterates through all the list items and sets the Selected
property for each list item to the value False. If multiple list items are selected, an exception is thrown.
One problem with the page discussed in this section is that the page must be posted back to the server each time you move an item from the first ListBox to the second ListBox. At the end of this chapter, you learn how to create a MultiSelectList
control, which uses a client-side script to get around this limitation.
The DropDownList
control enables you to display a list of options while requiring a minimum of screen real estate. A user can select only one option at a time when using this control.
The page in Listing 10.9 illustrates how you can use the DropDownList
control to display all the movie titles from the Movies database table (see Figure 10.8).
Example 10.9. ShowDropDownList.aspx
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <script runat="server"> protected void btnSubmit_Click(object sender, EventArgs e) { lblMovie.Text = ddlMovies.SelectedItem.Text; } </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Show DropDownList</title> </head> <body> <form id="form1" runat="server"> <div> <asp:DropDownList id="ddlMovies" DataSourceID="srcMovies" DataTextField="Title" DataValueField="Id" Runat="server" /> <asp:Button id="btnSubmit" Text="Submit" OnClick="btnSubmit_Click" Runat="server" /> <hr /> <asp:Label id="lblMovie" Runat="server" /> <asp:SqlDataSource id="srcMovies" SelectCommand="SELECT Id, Title FROM Movies" ConnectionString="<%$ ConnectionStrings:Movies %>" Runat="server" /> </div> </form> </body> </html>
The DropDownList
control renders an HTML <select>
tag. One problem with the HTML <select>
tag is that it has an infinite z index. In other words, you can’t place other objects, such as an absolutely positioned <div>
tag, in front of a DropDownList
control in a page.
One way to get around this problem is to use a third-party control such as the EasyListBox
control (available at http://www.EasyListBox.com). This control works fine when other objects are layered over it. It also supports several advanced features such as multiple columns and images in list items.
The RadioButtonList
control, like the DropDownList
control, enables a user to select only one list item at a time. The RadioButttonList
control displays a list of radio buttons that can be arranged either horizontally or vertically.
The page in Listing 10.10 illustrates how you can use the RadioButtonList
control to display a list of movie titles (see Figure 10.9).
Example 10.10. ShowRadioButtonList.aspx
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <script runat="server"> protected void btnSubmit_Click(object sender, EventArgs e) { lblMovie.Text = rblMovies.SelectedItem.Text; } </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Show RadioButtonList</title> </head> <body> <form id="form1" runat="server"> <div> <asp:RadioButtonList id="rblMovies" DataSourceID="srcMovies" DataTextField="Title" DataValueField="Id" RepeatColumns="3" Runat="server" /> <asp:Button id="btnSubmit" Text="Submit" Runat="server" OnClick="btnSubmit_Click" /> <hr /> <asp:Label id="lblMovie" Runat="server" /> <asp:SqlDataSource id="srcMovies" SelectCommand="SELECT Id, Title FROM Movies" ConnectionString="<%$ ConnectionStrings:Movies %>" Runat="server" /> </div> </form> </body> </html>
In Listing 10.10, the radio buttons are rendered in a three-column layout. The RadioButtonList
control includes three properties that have an effect on its layout:
RepeatColumns
—. The number of columns of radio buttons to display.
RepeatDirection
—. The direction that the radio buttons are repeated. Possible values are Horizontal and Vertical.
RepeatLayout
—. Determines whether the radio buttons are displayed in an HTML table. Possible values are Table and Flow.
By default, the radio buttons rendered by the RadioButtonList
control are rendered in an HTML table. If you set the RepeatLayout
property to the value Flow
, then the radio buttons are not rendered in a table. Even when the RadioButtonList
renders its items in Flow layout mode, you can specify multiple columns.
The ListBox
control is similar to the DropDownList
control with two important differences. First, the ListBox
control requires more screen real estate because it always displays a certain number of list items. Furthermore, unlike the DropDownList
control, the ListBox
control enables a user to select multiple items.
The page in Listing 10.11 illustrates how you can enable a user to select a single item from a ListBox
control (see Figure 10.10).
Example 10.11. ShowListBox.aspx
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <script runat="server"> protected void btnSubmit_Click(object sender, EventArgs e) { lblMovie.Text = lstMovies.SelectedItem.Text; } </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Show ListBox</title> </head> <body> <form id="form1" runat="server"> <div> <asp:ListBox id="lstMovies" DataSourceID="srcMovies" DataTextField="Title" DataValueField="Id" Rows="8" Runat="server" /> <p> <asp:Button id="btnSubmit" Text="Submit" OnClick="btnSubmit_Click" Runat="server" /> </p> <hr /> <asp:Label id="lblMovie" Runat="server" /> <asp:SqlDataSource id="srcMovies" SelectCommand="SELECT Id, Title FROM Movies" ConnectionString="<%$ ConnectionStrings:Movies %>" Runat="server" /> </div> </form> </body> </html>
Notice that the ListBox
control in Listing 10.11 includes a Rows
property. The Rows
property determines the number of list items that the ListBox
displays.
You can also configure the ListBox
control to enable a user to select multiple items. This is illustrated in the page in Listing 10.12 (see Figure 10.11).
Example 10.12. ShowMultipleListBox.aspx
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <script runat="server"> protected void btnSubmit_Click(object sender, EventArgs e) { foreach (ListItem item in lstMovies.Items) if (item.Selected) lblMovie.Text += "<li>" + item.Text; } </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Show Multiple ListBox</title> </head> <body> <form id="form1" runat="server"> <div> <asp:ListBox id="lstMovies" DataSourceID="srcMovies" DataTextField="Title" DataValueField="Id" SelectionMode="Multiple" Runat="server" /> <p> <asp:Button id="btnSubmit" Text="Submit" OnClick="btnSubmit_Click" Runat="server" /> </p> <hr /> <asp:Label id="lblMovie" EnableViewState="false" Runat="server" /> <asp:SqlDataSource id="srcMovies" SelectCommand="SELECT Id, Title FROM Movies" ConnectionString="<%$ ConnectionStrings:Movies %>" Runat="server" /> </div> </form> </body> </html>
Notice that the ListBox
in Listing 10.12 includes a SelectionMode
property that is set to the value Multiple
. A user can select multiple items from the ListBox
by using the Ctrl or Shift key when clicking more than one list item.
Most users don’t understand how to select multiple items from a ListBox
control. If you want to enable users to pick multiple items, a better approach is to use either the CheckBoxList
control (discussed in the next section) or the MultiSelectList
control (discussed in the final section of this chapter).
When you click the Submit button in Listing 10.12, all the selected list items are displayed in a Label control. The SelectedItem
, SelectedIndex
, and SelectedValue
properties return only the first list item selected. When multiple items are selected, you need to iterate through the Items collection of the ListBox
control to detect the selected items.
The CheckBoxList
control renders a list of check boxes. The check boxes can be rendered horizontally or vertically. Unlike the other List controls, a user always can select multiple items when using a CheckBoxList
control.
For example, the page in Listing 10.13 contains a CheckBoxList
control that renders its list items in two columns (see Figure 10.12).
Example 10.13. ShowCheckBoxList.aspx
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <script runat="server"> protected void btnSubmit_Click(object sender, EventArgs e) { foreach (ListItem item in cblMovies.Items) if (item.Selected) lblMovie.Text += "<li>" + item.Text; } </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Show CheckBoxList</title> </head> <body> <form id="form1" runat="server"> <div> <asp:CheckBoxList id="cblMovies" DataSourceID="srcMovies" DataTextField="Title" DataValueField="Id" RepeatColumns="2" Runat="server" /> <p> <asp:Button id="btnSubmit" Text="Submit" OnClick="btnSubmit_Click" Runat="server" /> </p> <hr /> <asp:Label id="lblMovie" EnableViewState="false" Runat="server" /> <asp:SqlDataSource id="srcMovies" SelectCommand="SELECT Id, Title FROM Movies" ConnectionString="<%$ ConnectionStrings:Movies %>" Runat="server" /> </div> </form> </body> </html>
When you click the Submit button, the values of the Text
property of any selected check boxes are displayed in a Label control. The selected check boxes are retrieved from the CheckBoxList
control’s Items
property.
The CheckBoxList
control includes three properties that affect its layout:
RepeatColumns
—. The number of columns of check boxes to display.
RepeatDirection
—. The direction in which the check boxes are rendered. Possible values are Horizontal and Vertical.
RepeatLayout
—. Determines whether the check boxes are displayed in an HTML table. Possible values are Table
and Flow
.
Normally, a CheckBoxList
control renders its list items in an HTML table. When the RepeatLayout
property is set to the value Flow
, the items are not rendered in a table.
The BulletedList
control renders either an unordered (bulleted) or ordered (numbered) list. Each list item can be rendered as plain text, a LinkButton
control, or a link to another web page.
For example, the page in Listing 10.14 uses the BulletedList
control to render an unordered list of movies (see Figure 10.13).
Example 10.14. ShowBulletedList.aspx
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Show BulletedList</title> </head> <body> <form id="form1" runat="server"> <div> <asp:BulletedList id="blMovies" DataSourceID="srcMovies" DataTextField="Title" Runat="server" /> <asp:SqlDataSource id="srcMovies" SelectCommand="SELECT Title FROM Movies" ConnectionString="<%$ ConnectionStrings:Movies %>" Runat="server" /> </div> </form> </body> </html>
You can control the appearance of the bullets that appear for each list item with the BulletStyle property. This property accepts the following values:
You can set BulletStyle
to Numbered
to display a numbered list. If you set this property to the value CustomImage
and assign an image path to the BulletImageUrl
property, then you can associate an image with each list item. For example, the page in Listing 10.15 displays an image named Bullet.gif
with each list item (see Figure 10.14).
Example 10.15. ShowBulletedListImage.aspx
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Show BulletedList Image</title> </head> <body> <form id="form1" runat="server"> <div> <asp:BulletedList id="blMovies" DataSourceID="srcMovies" DataTextField="Title" BulletStyle="CustomImage" BulletImageUrl="~/Images/Bullet.gif" Runat="server" /> <asp:SqlDataSource id="srcMovies" SelectCommand="SELECT Title FROM Movies" ConnectionString="<%$ ConnectionStrings:Movies %>" Runat="server" /> </div> </form> </body> </html>
You can modify the appearance of each list item by modifying the value of the DisplayMode
property. This property accepts one of the following values from the BulletedListDisplayMode
enumeration:
HyperLink
—. Each list item is rendered as a link to another page.
LinkButton
—. Each list item is rendered by a LinkButton control.
Text
—. Each list item is rendered as plain text.
For example, the page in Listing 10.16 displays a list of links to other websites (see Figure 10.15).
Example 10.16. ShowBulletedListHyperLinks.aspx
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Show BulletedList HyperLinks</title> </head> <body> <form id="form1" runat="server"> <asp:BulletedList id="blWebsites" DisplayMode="HyperLink" Target="_blank" Runat="server"> <asp:ListItem Text="Yahoo" Value="http://www.Yahoo.com" /> <asp:ListItem Text="Google" Value="http://www.Google.com" /> <asp:ListItem Text="Deja" Value="http://www.Deja.com" /> </asp:BulletedList> </form> </body> </html>
Each list item has both its Text
and Value
properties set. The Text
property contains the text that is displayed for the list item, and the Value
property contains the URL for the other website. Notice that the Target
property is set to the value blank
. When you click one of the hyperlinks, the page is opened in a new window.
All the List controls inherit from the base ListControl
class. If you are not happy with the existing List controls, there is nothing to prevent you from building your own.
In this section, we create a custom List control named the MultiSelectList
control. This control renders two list boxes and an Add and Remove button. You can click the buttons to move items between the two list boxes (see Figure 10.16).
The custom control uses client-side JavaScript to move the items between the two list boxes. Using JavaScript enables you to avoid posting the page back to the server each time a list item is moved. The client-side JavaScript is standards compliant so it will work with Internet Explorer 6.0, FireFox 1.0, and Opera 8.0.
The code for the custom MultiSelectList
is contained in Listing 10.17.
Example 10.17. MultiSelectList.cs
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; namespace MyControls { /// <summary> /// Enables you to select mulitple list items /// from two list boxes /// </summary> [ValidationProperty("SelectedItem")] public class MultiSelectList : ListControl, IPostBackDataHandler { private int _rows = 5; private Unit _UnSelectedWidth = Unit.Parse("300px"); private Unit _SelectedWidth = Unit.Parse("300px"); /// <summary> /// This control is contained in a div /// tag /// </summary> protected override HtmlTextWriterTag TagKey { get { return HtmlTextWriterTag.Div; } } protected override void AddAttributesToRender(HtmlTextWriter writer) { writer.AddStyleAttribute("position", "relative"); base.AddAttributesToRender(writer); } /// <summary> /// The number of rows of list items to display /// </summary> public int Rows { get { return _rows; } set { _rows = value; } } /// <summary> /// Name passed to client-side script /// </summary> private string BaseName { get { return ClientID + ClientIDSeparator; } } /// <summary> /// Name of unselected items list box /// </summary> private string UnselectedListName { get { return BaseName + "unselected"; } } /// <summary> /// Name of selected items list box /// </summary> private string SelectedListName { get { return BaseName + "selected"; } } /// <summary> /// Name of hidden input field /// </summary> private string HiddenName { get { return BaseName + "hidden"; } } /// <summary> /// Register client scripts /// </summary> protected override void OnPreRender(EventArgs e) { Page.RegisterRequiresPostBack(this); // Register hidden field Page.ClientScript.RegisterHiddenField(HiddenName, String.Empty); // Register Include File if (!Page.ClientScript.IsClientScriptIncludeRegistered ("MultiSelectList")) Page.ClientScript.RegisterClientScriptInclude("MultiSelectList", Page.ResolveUrl("~/ClientScripts/MultiSelectList.js")); // Register submit script string submitScript = String.Format("multiSelectList_submit('{0}')", BaseName); Page.ClientScript.RegisterOnSubmitStatement(this.GetType(), this.ClientID, submitScript); base.OnPreRender(e); } /// <summary> /// Render list boxes and buttons /// </summary> protected override void RenderContents(HtmlTextWriter writer) { // Render Unselected RenderUnselected(writer); // Render Buttons RenderButtons(writer); // Render Selected RenderSelected(writer); // Render clear break writer.AddStyleAttribute("clear", "both"); writer.RenderBeginTag(HtmlTextWriterTag.Br); writer.RenderEndTag(); } /// <summary> /// Render the buttons /// </summary> private void RenderButtons(HtmlTextWriter writer) { writer.AddStyleAttribute("float", "left"); writer.AddStyleAttribute(HtmlTextWriterStyle.Padding, "10px"); writer.AddStyleAttribute(HtmlTextWriterStyle.TextAlign, "center"); writer.RenderBeginTag(HtmlTextWriterTag.Div); string addScript = String.Format("return multiSelectList_add('{0}'),", BaseName); writer.AddAttribute(HtmlTextWriterAttribute.Onclick, addScript); writer.AddAttribute(HtmlTextWriterAttribute.Title, "Add Item"); writer.RenderBeginTag(HtmlTextWriterTag.Button); writer.Write("—>"); writer.RenderEndTag(); writer.WriteBreak(); string removeScript = String.Format("return multiSelectList_remove ('{0}'),", BaseName); writer.AddAttribute(HtmlTextWriterAttribute.Onclick, removeScript); writer.AddAttribute(HtmlTextWriterAttribute.Title, "Remove Item"); writer.RenderBeginTag(HtmlTextWriterTag.Button); writer.Write("<—"); writer.RenderEndTag(); writer.RenderEndTag(); } /// <summary> /// Render unselected list box /// </summary> private void RenderUnselected(HtmlTextWriter writer) { writer.AddStyleAttribute("float", "left"); writer.AddAttribute(HtmlTextWriterAttribute.Size, _rows.ToString()); writer.AddStyleAttribute(HtmlTextWriterStyle.Width, _UnSelectedWidth.ToString()); writer.AddAttribute(HtmlTextWriterAttribute.Id, UnselectedListName); writer.AddAttribute(HtmlTextWriterAttribute.Name, UnselectedListName); writer.AddAttribute(HtmlTextWriterAttribute.Multiple, "true"); writer.RenderBeginTag(HtmlTextWriterTag.Select); foreach (ListItem item in Items) if (!item.Selected) RenderListItem(writer, item); writer.RenderEndTag(); } /// <summary> /// Render selected list items /// </summary> private void RenderSelected(HtmlTextWriter writer) { writer.AddStyleAttribute("float", "left"); writer.AddAttribute(HtmlTextWriterAttribute.Size, _rows.ToString()); writer.AddStyleAttribute(HtmlTextWriterStyle.Width, _SelectedWidth.ToString()); writer.AddAttribute(HtmlTextWriterAttribute.Id, SelectedListName); writer.AddAttribute(HtmlTextWriterAttribute.Name, SelectedListName); writer.AddAttribute(HtmlTextWriterAttribute.Multiple, "true"); writer.RenderBeginTag(HtmlTextWriterTag.Select); foreach (ListItem item in Items) if (item.Selected) RenderListItem(writer, item); writer.RenderEndTag(); } /// <summary> /// Render a list item /// </summary> private void RenderListItem(HtmlTextWriter writer, ListItem item) { writer.AddAttribute(HtmlTextWriterAttribute.Value, item.Value); writer.RenderBeginTag(HtmlTextWriterTag.Option); writer.Write(item.Text); writer.RenderEndTag(); } /// <summary> /// Process postback data /// </summary> public bool LoadPostData(string postDataKey, System.Collections. Specialized.NameValueCollection postCollection) { EnsureDataBound(); ClearSelection(); string values = postCollection[HiddenName]; if (values != String.Empty) { string[] splitValues = values.Split(','), foreach (string value in splitValues) { Items.FindByValue(value).Selected = true; } } return false; } /// <summary> /// Required by the IPostBackDataHandler interface /// </summary> public void RaisePostDataChangedEvent() { } } }
Notice that the TagKey
property of the base ListControl
class is overridden. The elements of the control are contained in an HTML <div>
tag.
The MultiSelectList
renders its user interface in the RenderContents()
method. This method renders the two list boxes and button controls. Each unselected list item is rendered in the first list box and each selected item is rendered in the second list box.
Furthermore, the MultiSelectList
control implements the IPostBackDataHandler
interface. When a user posts a page that contains the MultiSelectList
control to the server, each item that the user selected is retrieved and the Items collection of the List control is updated.
The control takes advantage of a client-side JavaScript library contained in a file named MultiSelectList.js
. This JavaScript library is registered in the control’s OnPreRender()
method. The MultiSelectList.js
library is contained in Listing 10.18.
Example 10.18. MultiSelectList.js
function multiSelectList_add(baseName) { var unselectedList = document.getElementById(baseName + 'unselected'), var selectedList = document.getElementById(baseName + 'selected'), // Copy selected items var selectedItems = Array.clone(unselectedList.options); for (var i=0;i < selectedItems.length;i++) { if (selectedItems[i].selected) { var item = unselectedList.removeChild(selectedItems[i]); selectedList.appendChild(item); } } // Prevent post return false; } function multiSelectList_remove(baseName) { var unselectedList = document.getElementById(baseName + 'unselected'), var selectedList = document.getElementById(baseName + 'selected'), // Copy unselected items var selectedItems = Array.clone(selectedList.options); for (var i=0;i < selectedItems.length;i++) { if (selectedItems[i].selected) { var item = selectedList.removeChild(selectedItems[i]); unselectedList.appendChild(item); } } // Prevent post return false; } // This function executes when the page // is submitted. It stuffs all of the // selected items into a hidden field function multiSelectList_submit(baseName) { var hidden = document.getElementById(baseName + 'hidden'), var selectedList = document.getElementById(baseName + 'selected'), var values = new Array(); for (var i=0;i<selectedList.options.length;i++) values.push(selectedList.options[i].value); hidden.value = values.join(','), } Array.clone = function(arrItems) { var results = []; for (var i=0;i < arrItems.length; i++) results.push(arrItems[i]); return results; };
Listing 10.18 contains three JavaScript functions. The first two functions simply move list items from one list box to the other list box. The multiSelectList_submit()
function is called immediately before a page containing the MultiSelectList
control is posted to the server. This control records each of the selected list items (the items in the second list box) to a hidden form field.
The page in Listing 10.19 illustrates how you can use the MultiSelectList
control.
Example 10.19. ShowMultiSelectList.aspx
<%@ Page Language="C#" %> <%@ Register TagPrefix="custom" Namespace="MyControls" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <script runat="server"> protected void btnSubmit_Click(object sender, EventArgs e) { foreach (ListItem item in MultiSelectList1.Items) if (item.Selected) lblSelected.Text += String.Format("<li>{0} ({1})",item.Text,item.Value); } </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Show MultiSelectList</title> </head> <body> <form id="form1" runat="server"> <div> <b>Movies:</b> <asp:RequiredFieldValidator id="val" ControlToValidate="MultiSelectList1" Text="Required" Runat="server" /> <custom:MultiSelectList id="MultiSelectList1" DataSourceID="srcMovies" DataTextField="Title" DataValueField="Id" Runat="server" /> <asp:SqlDataSource id="srcMovies" SelectCommand="SELECT Id, Title FROM Movies" ConnectionString="<%$ ConnectionStrings:Movies %>" Runat="server" /> <p> <asp:Button id="btnSubmit" Text="Submit" Runat="server" OnClick="btnSubmit_Click" /> </p> <hr /> <asp:Label id="lblSelected" EnableViewState="false" Runat="server" /> </div> </form> </body> </html>
In the page in Listing 10.19, the MultiSelectList
control is bound to a SqlDataSource
control, which represents the contents of the Movies database table. You can select movie titles in the MultiSelectList
control by moving movie titles from one list box to the second list box. When you click the Submit button, the selected movies are displayed in a Label control.
In this chapter, you learned how to use List controls to display simple option lists. You saw the DropDownList
, RadioButtonList
, ListBox
, CheckBoxList
, and BulletedList
controls.
You also saw the common features of the List controls. You learned how to append data items to a List control and automatically post a form containing a List control back to the server.
Finally, you worked through the creation of a custom List control, which involved deriving a new control from the base ListControl
class. The custom List control takes advantage of client-side JavaScript to enable users to select multiple list items without requiring a page to be posted back to the server when each item is selected.