【问题标题】:List Boxes in VB.NETVB.NET 中的列表框
【发布时间】:2010-09-29 06:46:06
【问题描述】:

我想在 ListBox 中手动添加两个项目作为“活动”和“非活动”。当用户选择“ Active”时,我想获得值“ A”,并且选择“无活动”时,我想获得“ I”。

我如何在 VB.NET 中做到这一点。

【问题讨论】:

    标签: vb.net winforms listbox


    【解决方案1】:

    您使用的是 .NET 4 吗?如果是这样,最简单的解决方案可能是使用Tuple(Of String, String)。创建一个 ("Active", "A") 元组和另一个 ("Inactive", "I") 元组,并将它们添加到列表框中。然后将列表框的DisplayMember 属性设置为“Item1”,将ValueMember 设置为“Item2”。

    或者你可以对匿名类型做同样的事情。

    【讨论】:

    • 亲爱的乔恩,感谢您的回复。实际上,我有一个不可见的列表框,其中包含从存储过程填充的数据,并且我通过设置 DataSource 填充了它。同样,这些项目,我希望通过使用 items.add 将其填充到第二个列表框中。要求是我可以使用第二个列表框通过单击按钮来删除项目,因为无法从使用 DataSource 填充数据的列表框中删除项目。请指教。
    • @George:我看不出您的额外描述与问题的当前文本有何关联,也看不出为什么需要一个不可见的列表框开始。请使用更多上下文编辑您的问题。 (你甚至没有说这是 WPF、WinForms、ASP.NET 等)
    • 亲爱的 Jon,我正在使用 VB.NET [Windows Forms],它是一个桌面应用程序。我已经使用存储过程填充了一个列表框,并设置了列表框的 datasource 属性以获取从存储过程返回的信息。没有一个名为“删除”的按钮,当我从列表框中选择一个项目并单击“删除”时,该项目应该被删除。我尝试了“ListBox1.Items.RemoveAt(ListBox1.SelectedIndex),但它返回一个错误。现在我要做的是,当第一个列表框被填充时,我希望另一个列表框也使用 Items.Add 来填充,所以我可以删除。
    • @George:你还没有说为什么你有这个隐藏的列表框......请把所有这些信息编辑到问题中,而不是使用 cmets。
    • 设置数据源后从列表框中删除项目
    【解决方案2】:

    ListboxItemCollection 是 Object 类型。您可以像这样创建自定义 ListItem

    Public Class Form1
    
        Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            BindListBox()
        End Sub
    
        Private Sub BindListBox()
            With ListBox1
                .Items.Add(New CustomListItem("Acitve", "A"))
                .Items.Add(New CustomListItem("Inactive", "I"))
                .DisplayMember = "Text"
            End With
        End Sub
    
        Private Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
            MsgBox(CType(ListBox1.SelectedItem, CustomListItem).Value)
        End Sub
    
    End Class
    
    
    ''Custom ListItem Class
    Public Class CustomListItem
        Dim _text As String
        Dim _value As String
    
        Sub New(ByVal text As String, ByVal value As String)
            Me._text = text
            Me._value = value
        End Sub
    
        Public ReadOnly Property Text() As String
            Get
                Return _text
            End Get
        End Property
    
        Public ReadOnly Property Value() As String
            Get
                Return _value
            End Get
        End Property
    End Class
    

    【讨论】:

      【解决方案3】:

      一个简单的选择

      Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
          Debug.Print(ListBox1.Items(ListBox1.SelectedIndex).ToString.Substring(0, 1))
      End Sub
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-24
        • 1970-01-01
        相关资源
        最近更新 更多