Question Text file input delimiter?

Slider

Member
Joined
Jun 11, 2009
Messages
22
Programming Experience
Beginner
Hi,

I am wanting to write an application which opens a delimited text file (either comma, pipe, colon, semi colon) and displays the file on the form. The same feature is in Excel when you import a data file. After selecting the file it shows the contents and you can choose the delimiter. Once the delimiter is chosen the data shown reflects this and updates to show the correctly formatted data.

This is what I am trying to achieve.

Would really appreciate some advice on this please.

Thank you.
 
Take a look at the TextFieldParser class in the help file, it has examples and should fit your needs, you would just need to create an If or Select Case statement to input the delimiter you want to use.

VB.NET:
Expand Collapse Copy
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\testfile.txt")
  Dim currentRow As String()
  MyReader.TextFieldType = FileIO.FieldType.Delimited
  [COLOR="Red"][B] MyReader.SetDelimiters(",")[/B][/COLOR]

   While Not MyReader.EndOfData
      Try
         currentRow = MyReader.ReadFields()
         Dim currentField As String

         For Each currentField In currentRow
            MsgBox(currentField)
         Next

      Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
          MsgBox("Line " & ex.Message & "is not valid and will be skipped.")
      End Try
   End While
End Using
 
many thanks for your response. I understand how to read the data in and separate into fields. What I am unsure is how to display the data in a grid on the form and once the correct delimiter is selected, the data on the grid is automatically formatted correctly. ie, at first it is just shown as a raw text file, after selecting the delimiter, the data is split into the fields.
 
This is how I set a CSV file into a DataGridView:
VB.NET:
Expand Collapse Copy
Dim dt As New DataTable
'add as many of these are you need
dt.Columns.Add("Type1", GetType(System.String))
dt.Columns.Add("Type2", GetType(System.String))
dt.Columns.Add("Type3", GetType(System.String))
Using sr As New StreamReader(filepath)
   While Not sr.EndOfStream
      Dim str() As String = sr.ReadLine.Split(",")
      dt.Rows.Add(str)
   End While
End Using
dgv1.Datasource = dt
 
many thanks for your response. I understand how to read the data in and separate into fields. What I am unsure is how to display the data in a grid on the form and once the correct delimiter is selected, the data on the grid is automatically formatted correctly. ie, at first it is just shown as a raw text file, after selecting the delimiter, the data is split into the fields.

What you want to do is input the info into a dataset or datatable. Within the loop format your datarow and add it to your datatable. After reading the file into your dataset, simply assign the datatable as the grids datasource.
 
Back
Top