简体   繁体   English

从VB.net中的列表框中获取文本

[英]Get Text from listbox in VB.net

in my aspx page I have 在我的aspx页面中

<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 我想做的是从选定的元素中获取文本,但我不知道如何执行此操作

You just have to use the listbox.SelectedItem.Text property : 您只需要使用listbox.SelectedItem.Text属性

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: 或使用LINQ单缸纸:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM