Subscribe

RSS Feed (xml)

Working with ListBoxes in ASP.NET

Use the System.Web.UI.WebControls.ListBox control to place a ListBox control.To
allow multiple values to be chosen from the ListBox, set the SelectionMode property to
Multiple.The default is Single.The SelectedIndex property can use used to determine
whether the user has selected any items from the ListBox.The ASPX page is as
follows:
<html>
<head>
<title>code0111vb</title>
</head>
<body>
<form id=”Form1” method=”post” runat=”server”>
<asp:ListBox
ID=”CountryListBox”
Runat=”server”
SelectionMode=”Multiple”>
<asp:ListItem Value=1>United States</asp:ListItem>
<asp:ListItem Value=2>United Kingdom</asp:ListItem>
<asp:ListItem Value=3>China</asp:ListItem>
<asp:ListItem Value=4>India</asp:ListItem>
</asp:ListBox><br>
<asp:Button
ID=”SubmitButton”
Runat=”server”
Text=”Submit”
OnClick=”Verify”>
</asp:Button>
<asp:Label
ID=”OutputLabel”
Runat=”server”>
</asp:Label>
</form>
</body>
</html>
In <script runat=”server” /> block or codebehind:
Public Sub Verify(sender As System.Object, e As System.EventArgs)
Dim myListItem As ListItem
If CountryListBox.SelectedIndex <> -1 Then
OutputLabel.Text = “You selected: “
If CountryListBox.SelectionMode = ListSelectionMode.Single Then
OutputLabel.Text += “<b>” & _
CountryListBox.SelectedItem.Text & “</b>”
Else
For Each myListItem In CountryListBox.Items
If myListItem.Selected Then
OutputLabel.Text += “<b>” & myListItem.Text & _
“</b>, “
End If
Next
End If
Else
OutputLabel.Text = “You didn’t selected any country!”
End If
End Sub

This example demonstrates how to determine which values a user selected from a multiple-
selection ListBox. First, you start with an If statement, which verifies whether the
user has selected an item.Then you parse through all the items in the ListBox to find the
number of items selected.You also use a LabelWeb Server Control to display the output
to the user. If you want to retrieve the value of the selected item, you use the following
statement:
CountryListBox.SelectedItem.Value
Note that for a multiple-selection ListBox, this will only return the first value.

No comments:

Archives

Variety in the Web World