【问题标题】:Reading from a list in a text file, ripping certain a line and showing in listbox, Visual studio 2010从文本文件中的列表读取,翻录某些行并显示在列表框中,Visual Studio 2010
【发布时间】:2012-12-13 04:16:54
【问题描述】:

我正在使用 vb 在 Visual Studio 2010 中创建条形码扫描程序。

我已经走了很远,但似乎被这个小问题卡住了。

我保存了一个文本文件,其中的数据显示如下:

0001#Unsmoked Middle Bacon
0002#Smoked Middle bacon
0003#Unsmoked Bits
0004#Smoked Bits
0005#Unsmoked Back
0006#Smoked Back
0007#Unsmoked Streaky
0008#Smoked Streaky

用#读取和分割字符串没有问题,我可以填充2个列表框,1个显示4位代码,另一个显示产品名称。 (这只是一个测试场景)

我真正想做的是在文件中搜索一个变量,该变量是用户输入的数字,例如“0004”,这将显示给我“烟熏位”。

我想我想逐行阅读,直到找到正确的数字,然后阅读可能使用 substr?你们可能在这里帮了我很多忙。

While Not sreader.EndOfStream                               
                lineIn = sreader.ReadLine()
                Dim elements() As String = Nothing                      
                elements = lineIn.Split("#")
                lstProdTest.Items.Add(elements(0))
                lstProdName.Items.Add(elements(1))
                PLUnumber(index) = elements(0) 
                itemName(index) = elements(1)
                numProds = numProds + 1
                index = index + 1
            End While

【问题讨论】:

    标签: arrays vb.net visual-studio-2010 loops text-files


    【解决方案1】:

    正如 Origin 所说,如果这个文件没有太大以至于消耗太多内存,那么读取数据一次是要走的路:

    Private _barcodes As Dictionary(Of Integer, String)
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'EDIT forgot to initialize _barcodes:
        _barcodes = New Dictionary(Of Integer, String)
        For Each line In IO.File.ReadAllLines("c:\path\to\file.txt")
            Dim data = line.Split("#"c)
            _barcodes.Add(CInt(data(0)), data(1))
        Next
    End Sub
    
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim input As String = InputBox("type the barcode to test, eg 0004:")
        Dim key As Integer = CInt(input)
        'if you entered 0004 then this will display Smoked Bits
        If _barcodes.ContainsKey(key) Then
            MessageBox.Show(_barcodes(key))
        Else
            MessageBox.Show("Key not found")
        End If
    End Sub
    

    请注意,这只是一个简单的示例,需要添加错误处理(对于丢失的文件、不正确的数据格式等)

    如果数据量很大,那么考虑使用数据库,sqlite 将是一个简单的选择

    【讨论】:

    • 我现在可以看到它是如何工作的 :) 我似乎在表单加载时出现错误。 “你调用的对象是空的。” _barcodes.Add(CInt(data(0)), data(1)) 有什么想法吗?
    • 谢谢 :) 对更大的程序稍作调整后,它现在可以完美运行了。
    【解决方案2】:

    正如他们所说,过早优化是万恶之源。而不是每次需要项目描述时都读取文件,而应该读取文件一次(在应用程序开始时),将其存储在内存中(可能作为Dictionary(of Integer, String)),然后在尝试获取时引用它物品的描述。

    您当然可以更进一步,创建一个自定义类来存储有关每个条目的附加信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多