0

为什么我的代码总是搜索最后一条记录而不是我搜索的记录,就像这样8850338005909

这是文本文件中的代码示例数据:

8501045891528,2271,"亚当斯·CNDY大厅
HNYLMN100S/36",57.25,36.00,4822,1,100,101,465
8850338001604,2271,"亚当斯·CNDY大厅
HNYLMN100S/36",57.25,36.00,4822,1,100,101,465
8850338005909,2271,"亚当斯·CNDY大厅
HNYLMN100S/36",57.25,36.00,4822,1,100,101,465
8850338002519,2312,"CLRTS CNDY COOL MINT
40S/60",27.75,60.00,7049,1,100,101,465 8850338001000,2313,"ADAMS GUM
CLRETSTWIN PK14GX2/1",66.50,1.00,4822,1,100,101,470
4804880224138,2315,"BGUIO OIL CKNG
16KG/1",978.00,1.00,6135,1,192,193,639

我的代码:

Private Sub Data2()
    Dim text As String = IO.File.ReadAllText("C:\ITEMRTV.txt")
    Dim index As Integer = text.IndexOf(TextBox1.Text)
    Dim Values() As String = Split(text, ",")
    If index >= 0 Then
        ' String is in file, starting at character "index"
        Label1.Text = Values(0) ' now contains first column value,
        Label2.Text = Values(1) ' contains second column, etc.
        Label3.Text = Values(2)
        Label4.Text = Values(3)
        Label5.Text = Values(4)
        Label6.Text = Values(5)
    End If
End Sub
4

1 回答 1

0

尝试这个:

Dim text As String = IO.File.ReadAllText("C:\ITEMRTV.txt")
Dim Values() As String = text.Split(New String() {",", Environment.NewLine}, StringSplitOptions.None)
Dim index As Integer = Array.IndexOf(Values, TextBox1.Text)

If index >= 0 Then
    Label1.Text = Values(index)
    Label2.Text = Values(index + 1)
    Label3.Text = Values(index + 2)
    Label4.Text = Values(index + 3)
    Label5.Text = Values(index + 4)
    Label6.Text = Values(index + 5)
End If

但是你应该分成行和列:

Dim text() As String = IO.File.ReadAllLines("C:\ITEMRTV.txt")
Dim s() As String

For Each line As String In text
    s = line.Split(","c)
    If s(0).Equals(TextBox1.Text, StringComparison.CurrentCultureIgnoreCase) _
    AndAlso s.Length > 5 Then
        Label1.Text = s(0)
        Label2.Text = s(1)
        Label3.Text = s(2)
        Label4.Text = s(3)
        Label5.Text = s(4)
        Label6.Text = s(5)
        Exit For
    End If
Next

您甚至可以创建自己的结构来保存数据,这是更好的选择。例如,Dictionary(Of Integer, List(Of String))为每个文件声明一个,因为第一个字段看起来像一个 ID,或者声明您自己的类来适当地保存每个字段。

于 2013-02-28T08:57:10.900 回答