【问题标题】:Displaying specific csv field info in visual basic listbox在 Visual Basic 列表框中显示特定的 csv 字段信息
【发布时间】:2014-10-17 18:48:44
【问题描述】:

我有一个 2 列的 csv 文件: 11111,0001.jpg 22222,0002.jpg 33333,0003.jpg

我正在 Visual Studio 2013 中构建一个 Visual Basic Windows 窗体应用程序。该应用程序将在一侧有一个文本框和浏览按钮。文本框显示使用浏览按钮选择的文件位置。应用程序的另一侧是两个列表框。我有 listbox1 显示我的 csv 文件的第一列。我希望第二个列表框 listbox2 仅显示 csv 文件第二列中的最后 4 个字符。到目前为止,这是我的代码。我不确定如何在字段中选择某些字符。

Public Class Form1
Dim streamer As IO.StreamReader

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    ListBox1.Items.Clear()
    ListBox2.Items.Clear()
    Dim ofd1 As New OpenFileDialog
    If ofd1.ShowDialog() = Windows.Forms.DialogResult.OK Then
        TextBox1.Text = ofd1.FileName
    End If
    streamer = IO.File.OpenText(ofd1.FileName)
    Label3.Text = IO.File.ReadAllLines(ofd1.FileName).Length
    Dim MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(ofd1.FileName)
    MyReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
    MyReader.Delimiters = New String() {","}
    Dim currentRow As String()
    While Not MyReader.EndOfData
        Try
            currentRow = MyReader.ReadFields()
            ListBox1.Items.Add(currentRow(0))
            ListBox2.Items.Add(currentRow(1))
        Catch ex As Exception

        End Try
    End While



End Sub

【问题讨论】:

    标签: vb.net


    【解决方案1】:

    只需使用 string.Substring 和 string.Length 的组合

    ListBox2.Items.Add(currentRow(1).Substring(currentRow(1).Length - 4))
    

    在扩展形式中相同,并且对长度值进行了一些检查

    Dim startPos = currentRow(1).Length - 4
    If startPos < 0 Then
        startPos = 0
    End If
    Dim last4CharString = currentRow(1).Substring(startPos)
    ListBox2.Items.Add(last4CharString)
    

    顺便说一句,我认为您可以删除这些行
    (您阅读整个文件只是为了发现存在的行,然后使用 TextFieldParser 再次阅读)

    streamer = IO.File.OpenText(ofd1.FileName)
    Label3.Text = IO.File.ReadAllLines(ofd1.FileName).Length
    

    改为在 TextFieldParser 循环中使用 lineCounter 并在每个循环中递增它。
    然后将最终值设置为 Label 文本。

    Dim lineCounter = 0
    While Not MyReader.EndOfData
        ....
        lineCounter +=1
    End While
    Label3.Text = lineCounter.ToString
    

    【讨论】:

      猜你喜欢
      • 2012-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-24
      • 2016-08-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多