Get Text from listbox in VB.net

3.1k Views Asked by At

in my aspx page I have

<asp:listbox class="myClass" id="lbFamilies" OnSelectedIndexChanged="lbFamilies_SelectedIndexChanged" runat="server"  SelectionMode="Multiple"
                                    Height="137px" AutoPostBack="True" EnableViewState="True"></asp:listbox>

And the following is in my codebehind

Protected Sub lbFamilies_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)

What I am trying to do is to get the text from the selected element, but I can't figure out how to do this

1

There are 1 best solutions below

1
Tim Schmelter On BEST ANSWER

You just have to use the listbox.SelectedItem.Text property:

Protected Sub lbFamilies_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Dim text As String = Nothing
    If lbFamilies.SelectedItem IsNot Nothing Then
        text = lbFamilies.SelectedItem.Text
    End If
End Sub

Thanks, if I have multiselect how would I go through separate elements

Then you have to use a loop:

Protected Sub lbFamilies_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Dim allSelectedTexts As New List(Of String)
    For Each item As ListItem In lbFamilies.Items
        If item.Selected Then
            allSelectedTexts.Add(item.Text)
        End If
    Next
    ' following is just a bonus if you want to concatenate them with comma '
    Dim result = String.Join(",", allSelectedTexts)
End Sub

or with a LINQ one-liner:

Protected Sub lbFamilies_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Dim result = String.Join(",", From item In lbFamilies.Items.Cast(Of ListItem)()
                                  Where item.Selected
                                  Select item.Text)
End Sub