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

时间:2015-06-09 14:27:32

标签: asp.net vb.net

在我的aspx页面中我有

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

以下是我的代码隐藏

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

我想要做的是从所选元素中获取文本,但我无法弄清楚如何执行此操作

1 个答案:

答案 0 :(得分:1)

您只需使用listbox.SelectedItem.Text property

          date      x
1.1 2013-09-01  80.86
1.2 2013-09-02  80.86
1.3 2013-09-03  80.86
1.4 2013-09-04  80.86
1.5 2013-09-05  80.86
1.6 2013-09-06  80.86
1.7 2013-09-07  80.86
2.1 2013-09-08   9.29
2.2 2013-09-09   9.29
2.3 2013-09-10   9.29
2.4 2013-09-11   9.29
2.5 2013-09-12   9.29
2.6 2013-09-13   9.29
2.7 2013-09-14   9.29
3.1 2013-09-15  20.57
3.2 2013-09-16  20.57
3.3 2013-09-17  20.57
3.4 2013-09-18  20.57
3.5 2013-09-19  20.57
3.6 2013-09-20  20.57
3.7 2013-09-21  20.57
4.1 2013-09-22  65.00
4.2 2013-09-23  65.00
4.3 2013-09-24  65.00
4.4 2013-09-25  65.00
4.5 2013-09-26  65.00
4.6 2013-09-27  65.00
4.7 2013-09-28  65.00
5.1 2013-09-29 606.00
5.2 2013-09-30 606.00
  

谢谢,如果我有多选,我将如何通过单独的元素

然后你必须使用一个循环:

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

或使用LINQ one-liner:

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