<asp:ListBox> Control

An <asp:ListBox> control creates a scrollable drop-down list from which one or more items can be selected, unlike the <asp:DropDownList> control which permits only one selection. Any number of list items can be made visible. Multiple items are selected by using Ctrl-Click and Shift-Click selection techniques. A ListBox can be created manually, through script, or by binding to a data source. The ListBox shown below is created by binding to the BookType field of the BooksDB.mdb database. More than one item can be selected.




Figure 6-46. Creating a multiple-selection ListBox from a database.

Format for ListBox Control

The general format for a ListBox control is shown below.

<asp:ListBox id="id" Runat="Server"
  AutoPostBack="True|False"
  DataSourceID="id"
  DataTextField="field"
  DataTextFormatString="{string}"
  DataValueField="field"
  Rows="n"
  SelectionMode="Multiple|Single"

    property="value"...

    OnSelectedIndexChanged="subprogram"
>

  <asp:ListItem
    Selected="False|True"
    Text="string"
    Value="value"
  />
  ...

</asp:ListBox>
Figure 6-47. General format for <asp:ListBox> control.

When manually coding an <asp:ListBox> control, an opening and closing tag is required within which appear one or more <asp:ListItem> entries giving the items from which to select. An item is coded with a single empty tag containing Value and Text properties; or, each item can be coded as a pair of open and close tags with the Text property as the enclosed string. If a Value property is not coded, the Text property is treated as the value of a selection. Items can be preselected by setting their Selected="True" property.

Any number of items can be displayed at one time in the scrollable ListBox. The default number is four items; you can set the Rows property for a different number of visible items. A ListBox normally is accompanied by a button to call a subprogram to process the chosen item or items. When restricted to one choice, the ListBox's AutoPostBack="True" property can be set along with OnSelectedIndexChanged to name the called subprogram.

Single Selection Lists

The format for a manually coded ListBox using basic settings is shown below. In this configuration the ListBox works like a DropDownList except that a default number of items are visible, only one of which can be selected. Because only a single item can be selected from the list, its AutoPostBack property is activated.



SelectedIndex: SelectedItem.Text:   
SelectedValue: SelectedItem.Value:  
Figure 6-48. Determining ListBox properties.
<SCRIPT Runat="Server">

Sub Get_Selection (Src As Object, Args As EventArgs)
	
  ItemIndex.Text = ListBox.SelectedIndex
  ItemValue1.Text = ListBox.SelectedValue
  ItemText.Text = ListBox.SelectedItem.Text
  ItemValue2.Text = ListBox.SelectedItem.Value

End Sub

</SCRIPT>

<form Runat="Server">

<asp:ListBox id="ListBox" Runat="Server"
  AutoPostBack="True"
  OnSelectedIndexChanged="Get_Selection">
  <asp:ListItem Value="1" Text="Item 1"/>
  <asp:ListItem Value="2" Text="Item 2"/>
  <asp:ListItem Value="3" Text="Item 3"/>
  <asp:ListItem Value="4" Text="Item 4"/>
  <asp:ListItem Value="5" Text="Item 5"/>
</asp:ListBox><br/><br/>

SelectedIndex: <asp:TextBox id="ItemIndex" Size="3" Runat="Server"/>
SelectedItem.Text: <asp:TextBox id="ItemText" Size="3" Runat="Server"/><br/>
SelectedValue: <asp:TextBox id="ItemValue1" Size="3" Runat="Server"/>
SelectedItem.Value: <asp:TextBox id="ItemValue2" Size="3" Runat="Server"/>

</form>
Listing 6-38. Code and script to determine ListBox selection and properties.

The items in a ListBox are indexed beginning with 0. The index of the selected item is given by the SelectedIndex property. Its value is given by the SelectedValue property. If an item is selected (its SelectedIndex is not -1), its value also is referenced through the SelectedItem.Value property; its text label is referenced through the SelectedItem.Text property.

With multiple items selectable in a ListBox, no pre-selected index value is established. Unlike a DropDownList, the first item in a ListBox is not automatically selected if no explicit selection has been made. Therefore, the ListBox's initial SelectedValue is null. When triggering a script with a separate Button (rather than posting back with an explicit selection), it is necessary to test the SelectedIndex property for a positive value before accessing the SelectedItem.Text and SelectedItem.Value properties. You can, however, set a Selected="True" property for any one item, making it the default choice, and avoid having to test for a selection.

Multiple Selection Lists

A ListBox permits multiple selections with Ctrl-Click or Shift-Click by coding SelectionMode="Multiple". In the following example, hold down the Ctrl or Shift key while making selections. Since more that one item can be selected, the AutoPostBack feature is inactive. The subprogram should not be called on the first of multiple selections. Therefore, a separate button is provided to call the subprogram after all selections are made.




SelectedItem.Text:    SelectedItem.Value:
Figure 6-49. Making multiple selections from a ListBox.
<SCRIPT Runat="Server">

Sub Get_Selection (Src As Object, Args As EventArgs)

  Dim Item As ListItem
  For Each Item in ListBox.Items
    If Item.Selected = True Then
      ItemText.Text &= Item.Text & " "
      ItemValue.Text &= Item.Value & " "
    End If
  Next

End Sub

</SCRIPT>

<form Runat="Server">

<asp:ListBox id="ListBox" Runat="Server"
  Rows="3"
  SelectionMode="Multiple">
  <asp:ListItem Value="1">Item 1</asp:ListItem>
  <asp:ListItem Value="2">Item 2</asp:ListItem>
  <asp:ListItem Value="3">Item 3</asp:ListItem>
  <asp:ListItem Value="4">Item 4</asp:ListItem>
  <asp:ListItem Value="5">Item 5</asp:ListItem>
</asp:Listbox>

<asp:Button Text="Select" OnClick="Get_Selection" Runat="Server"/><br>
<br/>
SelectedItem.Text: <asp:Label id="ItemText" EnableViewState="False" 
Runat="Server"/>
SelectedItem.Value: <asp:Label id="ItemValue" EnableViewState="False" 
Runat="Server"/>

</form>
Listing 6-39. Code and script to determine ListBox multiple selections.

A ListBox has an Items collection representing the set of items in the list. If more than one selection is permitted, then a For Each...Next loop must be set up to iterate through the items to discover those that have been selected (their Selected property is True). The Text and Value properties of these selected items can be extracted.

Scripting the ListBox List

As in the case with RadioButtonList, CheckBoxList, and DropDownList controls, a ListBox can use its Items collection's Add(), Insert(), RemoveAt(), and Clear() methods to programmatically build and edit its list items.

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

or

ListBox.Items.Add(New ListItem("text","value"))

ListBox.Items.Insert(index, New ListItem("text","value"))
ListBox.Items.RemoveAt(index)
ListBox.Items.Clear()

ListBox.Items.Count
Figure 6-50. General formats for creating and editing a ListBox through script.

The following example defines a ListBox with individual items added by a script when the page is loaded. The first and last items in the list are preselected.




Figure 6-51. Creating a ListBox through script.
<SCRIPT Runat="Server">

Sub Page_Load

  If Not Page.IsPostBack Then
    ListBox.Items.Add(New ListItem("Item 1", "1"))
    ListBox.Items.Add(New ListItem("Item 2", "2"))
    ListBox.Items.Add(New ListItem("Item 3", "3"))
    ListBox.Items.Add(New ListItem("Item 4", "4"))
    ListBox.Items.Add(New ListItem("Item 5", "5"))
    ListBox.Items(0).Selected = "True"
    ListBox.Items(ListBox.Items.Count - 1).Selected = "True"
  End If

End Sub

</SCRIPT>

<form Runat="Server">

<asp:ListBox id="ListBox" SelectionMode="Multiple" Runat="Server"/>

</form>
Listing 6-40. Code to create a ListBox through script.

Since list items are numbered beginning with 0, the index of the last item in the list is ListBox.Items.Count - 1 (one less than the item count).

Binding to a Data Source

Text and Value properties for a ListBox can be bound from an external data source. The following list is created by binding to an AccessDataSource and assigning Text and Value properties for the list from the BookType field of the BooksDB.mdb database. The selected item types from the ListBox are displayed in a GridView.

View Book Types



Figure 6-52. Creating a ListBox for populating a GridView from the BooksDB.mdb database.
<SCRIPT Runat="Server">

Sub Get_Book_Types (Src As Object, Args As EventArgs)
	
  '-- Check for selected items
  Dim FoundSelected As Boolean = False
  Dim Item As ListItem
  For Each Item in BookList.Items
    If Item.Selected Then
      FoundSelected = True
    Exit For
  End If
  Next
	
  If FoundSelected = True Then
	
    Dim SQLString As String
    SQLString = "SELECT BookID, BookTitle, BookPrice, BookQty FROM Books WHERE "

    For Each Item in BookList.Items
      If Item.Selected Then
        SQLString &= "BookType = '" & Item.Value & "' OR "
      End If
    Next

    SQLString = Left(SQLString, Len(SQLString) - 4)
    SQLString &= " ORDER BY BookID"
    BookSource2.SelectCommand = SQLString
		
  End If

End Sub

</SCRIPT>

<form Runat="Server">

<h3>View Book Types</h3>

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

<asp:ListBox id="BookList" Runat="Server"
  SelectionMode="Multiple"
  DataSourceID="BookSource1"
  DataTextField="BookType"
  DataValueField="BookType"/>

<asp:Button Text="Select Types" OnClick="Get_Book_Types" Runat="Server"/><br/>

<asp:AccessDataSource id="BookSource2" Runat="Server"
  DataFile="../Databases/BooksDB.mdb"/>
	
<asp:GridView id="BookGrid3" DataSourceID="BookSource2" Runat="Server"/>

</form>
Listing 6-41. Using a ListBox to populate a GridView with selected records.

The ListBox is populated with an AccessDataSource that selects DISTINCT BookType values from the database, using them as both the DataTextField and DataValueField of the ListBox. Items in the list can be formatted differently from their default displays by supplying a DataTextFormatString for the ListBox to include additional text or formatting tags.

Notice that the AccessDataSource associated with the GridView does not supply a SELECT command. Therefore, the GridView is not populated with an initial record from the database. Because no data are bound to the GridView, it does not display data and is, therefore, invisible when the page opens.

When the button is clicked, subprogram Get_Book_Types is called to generate an appropriate SQL SELECT statement to extract and display selected book types from the database. Before composing and issuing this statement, however, a check must be made as to whether any items have been selected from the ListBox. If not, no SQL statement needs to be issued against the database.

Sub Get_Book_Types (Src As Object, Args As EventArgs)

  '-- Check for selected items
  Dim FoundSelected As Boolean = False
  Dim Item As ListItem
  For Each Item in BookList.Items
    If Item.Selected Then
      FoundSelected = True
    Exit For
  End If
  Next
  ...

End Sub
Listing 6-42. Testing for selected items from a ListBox.

As in a previous script for testing CheckBoxList selections, a flag is set indicating whether at least one selection has been made from the ListBox. If so, the FoundSelected flag is set to True and a SELECT statement is created.

Sub Get_Book_Types (Src As Object, Args As EventArgs)

  ...

  If FoundSelected = True Then
	
    Dim SQLString As String
    SQLString = "SELECT BookID, BookTitle, BookPrice, BookQty FROM Books WHERE "

    For Each Item in BookList.Items
      If Item.Selected Then
        SQLString &= "BookType = '" & Item.Value & "' OR "
      End If
    Next

    SQLString = Left(SQLString, Len(SQLString) - 4)
    SQLString &= " ORDER BY BookID"
    BookSource2.SelectCommand = SQLString
		
  End If

End Sub
Listing 6-43. Composing a SELECT statement for selected items from a ListBox.

As many

"BookType = '" & Item.Value & "' OR "

clauses are added to the SELECT statement as there are items selected from the ListBox. At completion of the loop, the SELECT statement includes extra " OR " characters on the end of the string which need to be removed; plus, the "ORDER BY BookID" clause needs to be added. The completed statement is assigned as the SelectCommand property of the AccessDataSource that populates the GridView, producing a list of selected book types.

Note that if the button is clicked and no items are selected from the ListBox that no SELECT statement is composed or issued, and the ListBox and GridView retain their previous displays. Since both controls take part in the page's View State, they both retain their previous values.