2014-10-17 68 views
2

我有2列CSV文件: 11111,0001.jpg 22222,0002.jpg 33333,0003.jpg顯示特定CSV字段信息在Visual Basic列表框中

我建立一個Visual Basic Windows窗體在Visual Studio 2013應用程序。該應用程序將在一邊有一個文本框和瀏覽按鈕。文本框顯示使用瀏覽按鈕選擇的文件位置。在應用程序的另一邊是兩個列表框。我有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 

回答

0

只需使用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,並在每個循環中增加它。
然後將最終值設置爲標籤文本。

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