VB.NET在ListBox中搜索字符串并返回特定数据

时间:2018-07-31 11:41:20

标签: vb.net search listbox

我有一个填充的列表框。每个项目都有一个带有ID和值的数据字符串。我将如何搜索ID并接收价格信息?

如果我搜索'itemColor',我希望它在新的msgbox中返回每种引导色。

itemName="boots" itemCost="$39" itemColor="red"
itemName="boots" itemCost="$39" itemColor="green"
itemName="boots" itemCost="$39" itemColor="blue"
itemName="boots" itemCost="$39" itemColor="yellow"

我知道有多种更简便的方法可以做到这一点,但我需要这样做。

谢谢!

2 个答案:

答案 0 :(得分:0)

这是涉及将文本解析为XML的一种方法:

' Here's Some Sample Text
Dim listboxText As String = "itemName=""boots"" itemCost=""$39"" itemColor=""red"""

' Load XML and Convert to an Object
Dim xmlDocument As New System.Xml.XmlDocument
xmlDocument.LoadXml("<item " & listboxText & "></item>")
Dim item = New With {.ItemName = xmlDocument.DocumentElement.Attributes("itemName").Value,
        .ItemCost = xmlDocument.DocumentElement.Attributes("itemCost").Value,
        .ItemColor = xmlDocument.DocumentElement.Attributes("itemColor").Value}

' Write It Out as a Test
Console.WriteLine(item.ItemName & " " & item.ItemCost & item.ItemColor)
Console.Read()

答案 1 :(得分:0)

创建一个类(或结构),适当的属性,默认构造函数,参数化构造函数和.ToString的Override。

Public Class Item
    Public Property Name As String
    Public Property Cost As String
    Public Property Color As String
    Public Sub New()
    End Sub
    Public Sub New(sName As String, sCost As String, sColor As String)
        Name = sName
        Cost = sCost
        Color = sColor
    End Sub
    Public Overrides Function ToString() As String
        Return $"{Name} - {Cost} - {Color}"
    End Function
End Class

Item对象被添加到调用参数化构造函数的列表框中。列表框在对象上调用.ToString以确定要显示的内容。

Private Sub FillList()
    ListBox3.Items.Add(New Item("boots", "$39", "red"))
    ListBox3.Items.Add(New Item("boots", "$39", "green"))
    ListBox3.Items.Add(New Item("boots", "$39", "blue"))
    ListBox3.Items.Add(New Item("boots", "$39", "yellow"))
End Sub

自从我们将Item对象添加到列表框中以来,我们可以将每个列表项强制转换回Item类型并访问其属性。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim sb As New StringBuilder
    For Each i In ListBox3.Items
        sb.AppendLine(DirectCast(i, Item).Color)
    Next
    MessageBox.Show(sb.ToString)
End Sub