<asp:RadioButtonList> Control

ASP.NET provides several list controls with features that permit expanded programming access to radio buttons and other controls presenting lists of items from which to choose. List controls can be created with scripts rather than in hard-coded XHTML; they also can be bound to data drawn from databases. These features mean that controls such as RadioButtons can be generated dynamically to represent live information. As a quick example, the following set of radio buttons is created by extracting BookType field values from the BooksDB.mdb database and automatically producing a button for each value.

Book Types






Figure 6-14. Creating a set of radio buttons from a database.

Format for RadioButtonList Control

Unlike the <asp:RadioButton> control, which creates a single radio button, the <asp:RadioButtonList> control creates a group of buttons. The buttons can be created manually or by script, or the control can be bound to a data source for automatic generation of buttons. The general format for the RadioButtonList control is shown below.

<asp:RadioButtonList id="id" Runat="Server"
  AutoPostBack="False|True"
  CellPadding="n"
  CellSpacing="n"
  DataSourceID="id"
  DataTextField="field"
  DataTextFormatString="string"
  DataValueField="field"
  OnSelectedIndexChanged="subprogram"
  RepeatColumns="n"
  RepeatDirection="Vertical|Horizontal"
  RepeatLayout="Table|Flow"
  TextAlign="Right|Left"
    property="value"...
>
	
  <asp:ListItem
    Selected="False|True"
    Text="label"
    Value="value"
  />
  ...
	
</asp:RadioButtonList>
Figure 6-15. General format for <asp:RadioButtonList> control.

An <asp:RadioButtonList> control contains one or more <asp:ListItem> controls, each representing a radio button in the set. A RadioButtonList can be created manually by defining a ListItem for each button as shown in the following example.



Figure 6-16. A coded RadioButtonList.
<asp:RadioButtonList id="ButtonList" Runat="Server">
  <asp:ListItem Text="Red" Value="#FF0000" Selected="True"/>
  <asp:ListItem Text="Green" Value="#00FF00"/>
  <asp:ListItem Text="Blue" Value="#0000FF"/>
</asp:RadioButtonList>
Listing 6-15. Code to create a RadioButtonList.

The Text property gives the button's label, the Value property sets the value of the button, and the Selected="True" property prechecks the button. (Note this is different from the Checked property of the RadioButton control; also, the RadioButtonList control does supply values for the buttons.) The TextAlign property displays the button's label to the Left or Right (default) of the button.

When a RadioButtonList control is rendered in XHTML, the buttons are formatted within a <table> tag to control their alignment. As a result, the amount of spacing surrounding the buttons can be set with the CellPadding and/or CellSpacing attributes.

When a RadioButtonList contains a large number of buttons, they do not have to be displayed in a single, long column. The RepeatColumns property can be set to the number of columns across which to display the buttons. The RepeatDirection property sequences the buttons vertically (down the columns) or horizontally (across the rows).




Figure 6-17. Displaying a RadioButtonList across columns.
<asp:RadioButtonList id="ButtonList" Runat="Server"
  RepeatColumns="3"
  RepeatDirection="Horizontal">
  <asp:ListItem Text="Button 1"/>
  <asp:ListItem Text="Button 2"/>
  <asp:ListItem Text="Button 3"/>
  <asp:ListItem Text="Button 4"/>
  <asp:ListItem Text="Button 5"/>
  <asp:ListItem Text="Button 6"/>
  <asp:ListItem Text="Button 7"/>
  <asp:ListItem Text="Button 8"/>
  <asp:ListItem Text="Button 9"/>
</asp:RadioButtonList>
Listing 6-16. Code to create a columnar RadioButtonList.

Determining Button Properties

Several properties can be extracted from a RadioButtonList in order to determine which of the buttons is checked and what is its value. The SelectedIndex property references the index value of the checked button, numbered beginning with 0. If no button is checked, then SelectedIndex is -1. The SelectedValue property gives the value associated with a selected button. If no button from the list is selected, the SelectedValue is null.

When a button is selected, SelectedItem.Value refers to its data Value and SelectedItem.Text refers to its Text label. If no Value property is specified for a button, its Text property is reported as its value. These properties can be accessed only when a button is selected, that is, when the SelectedIndex property of the list is not -1. Therefore, scripts must check this property to ensure that its value is not -1 before attempting to access the SelectedItem.Value or SelectedItem.Text property of the control.

The following output shows properties that are script-accessible through a RadioButtonList. Click the "Select" button before checking a radio button to view the initial SelectedIndex (-1) and SelectValue ("") settings. SelectedItem.Value and SelectedItem.Text properties are reported only after a radio button is checked.






SelectedIndex: SelectedValue:
SelectedItem.Text: SelectedItem.Value:
Figure 6-18. Displaying a RadioButtonList's selected properties.
<SCRIPT Runat="Server">

Sub Get_Button (Src As Object, Args As EventArgs)

  SelectedIndex.Text = ButtonList.SelectedIndex
  SelectedValue.Text = ButtonList.SelectedValue
	
  If ButtonList.SelectedIndex <> -1 Then
    ButtonText.Text = ButtonList.SelectedItem.Text
    ButtonValue.Text = ButtonList.SelectedItem.Value
  End If

End Sub

</SCRIPT>

<form Runat="Server">

<asp:RadioButtonList id="ButtonList" Runat="Server">
  <asp:ListItem Value="R" Text="Red"/>
  <asp:ListItem Value="G" Text="Green"/>
  <asp:ListItem Value="B" Text="Blue"/>
</asp:RadioButtonList>

<asp:Button Text="Select" OnClick="Get_Button" Runat="Server"/>

SelectedIndex: <asp:TextBox id="SelectedIndex" Size="1" Runat="Server"/>
SelectedValue: <asp:TextBox id="SelectedValue" Size="1" Runat="Server"/>
SelectedItem.Value: <asp:TextBox id="ButtonValue" Size="1" Runat="Server"/>
SelectedItem.Text: <asp:TextBox id="ButtonText" Size="1" Runat="Server"/>

</form>
Listing 6-17. Code and script to display RadioButtonList's selected properties.

With a RadioButtonList it is not necessary to test each and every button to determine if it is checked or to determine its value, which is the case when using RadioButton controls. The SelectedIndex property reports which one of the entire set of buttons is checked; the SelectedValue property gives the Value of the selected button, if any; the SelectedItem.Value and SelectedItem.Text properties reference the single checked button within the entire group.

If one of the buttons in the list is prechecked, then it is not necessary to test for a positive SelectedIndex value prior to retrieving a button's SelectedItem.Value or SelectedItem.Text setting. Valid Text and Value properties always will be available to the script.

As in the case of the RadioButton control, the buttons themselves can trigger post-back by coding AutoPostBack="True" for the RadioButtonList. To specify a subprogram to call when a button is clicked, code the OnSelectedIndexChanged event handler giving the subprogram name.

Scripting the Items Collection

An <asp:RadioButtonList> has an Items collection comprised of all its <asp:ListItem> entries. This collection is a programmable object with properties and methods permitting script manipulation of the list. Throught use of its Items collection, a RadioButtonList can be built programmatically rather than manually.

Adding Items to a List

When using script to build a RadioButtonList, only the <asp:RadioButtonList> control needs to be coded on the page. ListItems are added programmatically rather than coding individual <asp:ListItem> controls for buttons in the list. Script commands pertinent to creating buttons for a RadioButtonList are shown below.

Dim NewItem As ListItem
NewItem = New ListItem("text","value")
RadioButtonList.Items.Add(NewItem)

or

RadioButtonList.Items.Add(New ListItem("text","value"))
Figure 6-19. General formats for creating a RadioButtonList through script.

A radio button is created as a new ListItem data type and is assigned Text and Value properties. It is then added to the Items collection of a RadioButtonList with the collection's Add() method, using the lists' id as reference. As shown above, these steps can be combined into a single statement.

Both Text and Value properties can be supplied for the new item. If only a Value is supplied, i.e., New ListItem("value"), then that value is used as both the Text label and the Value of the control.

The coding and scripting technique to build a RadioButtonList programmatically is shown in the example below.



Figure 6-20. A RadioButtonList created through script.
<SCRIPT Runat="Server">

Sub Page_Load

  If Not Page.IsPostBack Then
    ButtonList.Items.Add(New ListItem("Red","R"))
    ButtonList.Items.Add(New ListItem("Green","G"))
    ButtonList.Items.Add(New ListItem("Blue","B"))
    ButtonList.Items(0).Selected = True
  End If

End Sub

</SCRIPT>

<form Runat="Server">

<asp:RadioButtonList id="ButtonList" Runat="Server"/>

</form>
Listing 6-18. Script to create a RadioButtonList.

Notice that the RadioButtonList is generated only the first time the page is loaded. As a server control, it participates in the page's View State, and the list and its property settings are retained on subsequent page postings.

Items are added to the collection in the order of the Add() statements, with items having index values beginning with 0. This index value (RadioButtonList.Items(index)) can be used to point to a particular button in the list, for example, to preselect a button as is done in the above script (ButtonList.Items(0).Selected = True).

Inserting Items into a List

Item indexing also permits items to be added at particular locations in the list by using the Items collection's Insert() method. Its general format is shown below.

RadioButtonList.Items.Insert(index, New ListItem("text","value"))
Figure 6-21. General format for inserting a button into a RadioButtonList.

For example, the statements in Listing 6-19 insert two new radio buttons into the previous RadioButtonList. The first button (index = 0) has "Black" and "B" Text and Value properties. The last button in the list is assigned "White" and "W" Text and Value properties. It is positioned last in the list by using the Count property of the list to determine the number of buttons it contains. After inserting the first button, Count = 4. This value is used as the index to the last position in the list, making the inserted button the fifth button in the list.

ButtonList.Items.Insert(0, New ListItem("Black","B"))
ButtonList.Items.Insert(ButtonList.Items.Count, New ListItem("White","W"))
Listing 6-19. Script to insert a radio button into a RadioButtonList.

When the above script is run, the revised RadioButtonList shown in Figure 6-22 is produced.





Figure 6-22. Inserted buttons in a RadioButtonList.

Removing and Clearing Items from a List

The RemoveAt(index) method is used to remove the button at index position in a RadioButtonList. The Items.Clear() method is used to clear the entire list of items. General formats for these two methods are shown below.

RadioButtonList.Items.RemoveAt(index)
RadioButtonList.Items.Clear()
Figure 6-23. General formats for removing buttons from a RadioButtonList.

Iterating an Items Collection

The most direct method of determining which button in a RadioButtonList is checked is by referencing its SelectedValue property. If no button has been selected, then the property is null. If a button has been selected (its SelectedIndex property is not -1), then the list's SelectedItem.Text and SelectedItem.Value properties can be accessed.

An alternative to checking for a selected button is to iterate its Items collection. A Visual Basic For Each...Next loop, available for iterating any collection, can be used to sequence through the items in a RadioButtonList. The following script, for example, determines which of the accompanying radio buttons is checked and reports its Text and Value properties.




  Item.Text: Item.Value:
Figure 6-24. Iterating an Items collection.
<SCRIPT Runat="Server">

Sub Page_Load

  If Not Page.IsPostBack Then
    ButtonList.Items.Add(New ListItem("Red","R"))
    ButtonList.Items.Add(New ListItem("Green","G"))
    ButtonList.Items.Add(New ListItem("Blue","B"))
  End If

End Sub

Sub Get_Selected_Button (Src As Object, Args As EventArgs)

  Dim Item As ListItem
  For Each Item in ButtonList.Items
    If Item.Selected = True Then
      TextProperty.Text = Item.Text
      ValueProperty.Text = Item.Value
    End If
  Next

End Sub

</SCRIPT>

<form Runat="Server">

<asp:RadioButtonList id="ButtonList" Runat="Server"/>

<asp:Button Text="Get Selected" OnClick="Get_Selected_Button" Runat="Server"/>
Item.Text: <asp:TextBox id="TextProperty" Size="1" Runat="Server"/>
Item.Value: <asp:TextBox id="ValueProperty" Size="1" Runat="Server"/>

</form>
Listing 6-20. Code to iterate the Items collection of a RadioButtonList.

The following general format is used to set up an iteration through the items in a RadioButtonList collection. This format also is used when iterating any ASP.NET collection, and appears throughout these tutorials.

Dim ItemVariable As ListItem

For Each ItemVariable in RadioButtonList.Items

  ...ItemVariable.property

Next
Figure 6-25. General format for iterating a collection.

A collection of Items is iterated by first defining a variable to represent each item in the list. In the above example, variable Item is declared as a ListItem type for this purpose. (Any programmer-supplied name can be used for the variable; it does not have to be Item.) Then the loop iterates through the list’s Items collection, assigning each ListItem object, in turn, to variable Item. Thus, Item.Selected refers to the Selected property of whichever item is being pointed to during the iteration. If that item is selected, then its Item.Text and Item.Value properties are retrieved.

Binding to a Data Source

One of the main advantages of using a RadioButtonList rather than a set of individual RadioButton controls is that the former can be bound to a data source from which Text and Value properties are drawn. This can be accomplished without writing any script, but by associating the RadioButtonList with a data source control.

The following list is created by binding a RadioButtonList to an AccessDataSource and assigning Text and Value properties for the buttons from data fields in the database. This example uses values from the BookType field of the BooksDB.mdb database as both Text and Value properties. When a button is selected, a script is run to extract that book type from the database for display in a GridView control.

View Book Types


BookIDBookTitleBookPriceBookQty
DB111Oracle Database$69.9910
DB222Databases in Depth$29.956
DB333Database Processing$136.6512
DB444Access Database Design$34.9525
DB555SQL Server 2005$29.990

Figure 6-26. Using a RadioButtonList to populate a GridView from the BooksDB.mdb database.
<SCRIPT Runat="Server">

Sub Preselect_Button (Src As Object, Args As EventArgs)

  RadioList.Items(0).Selected = True

End Sub

Sub Get_Book_Type (Src As Object, Args As EventArgs)

  Dim SQLString As String 
  SQLString= "SELECT BookID, BookTitle, BookPrice, BookQty " & _
             "FROM Books WHERE BookType='" & RadioList.SelectedValue & "'"
  GridSource.SelectCommand = SQLString

End Sub

</SCRIPT>

<form Runat="Server">

<h3>View Book Types</h3>

<asp:AccessDataSource id="RadioSource" Runat="Server"
  DataFile="../Databases/BooksDB.mdb"
  SelectCommand="SELECT DISTINCT BookType FROM Books ORDER BY BookType"/>

<asp:RadioButtonList id="RadioList" Runat="Server"
  RepeatColumns="3"
  RepeatDirection="Vertical"
  DataSourceID="RadioSource"
  DataTextField="BookType"
  DataValueField="BookType"
  AutoPostBack="True"
  OnDataBound="Preselect_Button"
  OnSelectedIndexChanged="Get_Book_Type"/>

<asp:AccessDataSource id="GridSource" Runat="Server"
  DataFile="../Databases/BooksDB.mdb"
  SelectCommand="SELECT BookID, BookTitle, BookPrice, BookQty FROM Books
                 WHERE BookType = 'DataBase'"/>

<asp:GridView id="BookGrid" DataSourceID="GridSource" Runat="Server"/>

</form>
Listing 6-21. Code to use a RadioButtonList to populate a GridView from a database.

No scripting is required to create the RadioButtonList. It is produced automatically by associating an AccessDataSource with the RadioButtonList control. The AccessDataSource issues a SELECT statement to return a recordset of BookType values from the Books table. Since duplicate BookType values appear in the records, only single instances of unique (DISTINCT) values are returned. This recordset is linked to the RadioButtonList through the latter's DataSourceID property, naming the id of the AccessDataSource. A button is created for each returned record. The BookType value is used for both the Text property (DataTextField) and Value property (DataValueField) of the button.

When a radio button selection is made, the Get_Book_Type subprogram is called. The buttons themselves call the subprogram by coding AutoPostBack="True" and OnSelectedIndexChanged="Get_Book_Type" for the RadioButtonList. The SelectedValue property of the selected button (one of the BookType values assigned to the button during database binding) is concatenated within a SELECT statement to extract book records of that type. The composed statement is assigned as the SelectCommand property of the AccessDataSource that feeds the GridView, thus producing a listing of that book type.

The AccessDataSource for the GridView initially selects records with an BookType of "Database" in order to populate the GridView when the page loads. However, the RadioButtonList does not reflect this selection since no button has yet been clicked. The need, then, is to programmatically select this button for compatibility with initial GridView display.

RadioButtonList Events and Handlers

All server controls recognize various events that surround them. For example, a Load event occurs when they are loaded into the page, a DataBound event occurs when they bind to a data source, and the RadioButtonList recognizes a SelectedIndexChanged event that occurs when a button is clicked. Server controls also provide event handlers to react to these events and call subprograms. The RadioButtonList's OnSelectedIndexChanged handler reacts to a button click when AutoPostBack is set for the control. A RadioButtonList also recognizes a DataBound event which is used here to deal with the need to select a button when the list first loads.

A button in a RadioButtonList cannot be preselected until after the list is built, that is, until after its AccessDataSource binds to the list. When this occurs, a RadioButtonList produces a DataBound event signaling that the list is built. This event can be scripted with an OnDataBound event handler attached to the list, in this case calling a subprogram to select a button after the list loads.

An OnDataBound event handler appears in the above RadioButtonList to call subprogram Preselect_Button when data binding with its AccessDataSource is finished. This subprogram then selects the first button in the list, RadioList.Items(0).Selected = True, checking the "Database" button to match initial GridView display.

Using a DataTextFormatString

A RadioButtonList supplies a DataTextFormatString to format the text labels appearing next to the buttons when the labels are supplied by an external data source through the DataTextField property. The DataTextFormatString property uses a format string in the format "{0}" to apply special styling, if preferred, to the text. (See the "Format Strings" tutorial.)

In the following example, a format string is provided to color and underline the text labels supplied by the BookType field of the BooksDB.mdb database.

View Book Types






Figure 6-27. Applying a DataTextFormatString to a RadioButtonList.
<form Runat="Server">

<h3>View Book Types</h3>

<asp:AccessDataSource id="RadioSource" Runat="Server"
  DataFile="../Databases/BooksDB.mdb"
  SelectCommand="SELECT DISTINCT BookType FROM Books ORDER BY BookType"/>
	
<asp:RadioButtonList id="RadioList" Runat="Server"
  DataSourceID="RadioSource"
  DataTextField="BookType"
  DataTextFormatString="<span style='color:red'><u>{0}</u></span>"
  DataValueField="BookType"/>

</form>
Listing 6-22. Code to apply a DataTextFormatString to a RadioButtonList.

Labels are extracted from the BookTypes field and displayed with the DataTextField property. As a database text field, the labels do not include formatting information. This formatting is supplied by the DataTextFormatString property. In this case, the format string placeholder, "{0}", is embedded within XHTML tags which apply formatting to the substituted labels. Note that quotes inside the format string, which itself is enclosed in quotes, must be single quotes (apostrophes) to alternate delimiters.