Link to home
Start Free TrialLog in
Avatar of Giulia Ayumi
Giulia AyumiFlag for Brazil

asked on

Import a txt file into a DataGridView and TextBox

Hello! I'm finding a way that i can import a txt file into the DataGridView, i've managed to do it in VB6 but i'm having a little of trouble to do that on VS2015

Here is the sample File:

      ----      ----      ----      ----      ----
      ----      ----      ----      ----      ----
      ----      ----      ----      ----      ----
      ----      ----      ----      ----      ----
      ----      ----      ----      ----      ----
      ----      ----      ----      ----      ----
      ----      ----      ----      ----      ----
      ----      ----      ----      ----      ----
      ----      ----      ----      ----      ----
      ----      ----      ----      ----      ----
      ----      ----      ----      ----      ----
      ----      ----      ----      ----      ----
      ----      ----      ----      ----      ----
      ----      ----      ----      ----      ----
      ----      ----      ----      ----      ----
NAME: JON
JOB: IT HELPER
PLACE: ADMIN
COMPANY: COMPANY NAME


Where "----" would be the data, and the last 4 lines would be put into TextBox excluding the caption "NAME: " etc.

The problem is, i've been trying to find a solution for that but it always end in a problem, i have tried data table but i'm not much familiar with it.

There is a little part of the code i'm trying to do:

        If Open.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
            MyFile = Open.FileName
            Dim oInfile As New System.IO.StreamReader(MyFile)
            Dim tblInfile As New DataTable
            tblInfile.Columns.Add(6)

            Do While Not oInfile.EndOfStream
                Dim aryDataIn() = Split(oInfile.ReadLine, vbTab)
                tblInfile.Rows.Add(aryDataIn)
            Loop

            DataLogGrid.DataSource = tblInfile

        End If
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Does this information
NAME: JON
JOB: IT HELPER
PLACE: ADMIN
COMPANY: COMPANY NAME

Open in new window

appears only once in the text file or will it be repeated multiple times with the text file?
Avatar of Giulia Ayumi

ASKER

The file is static which means all the "----" contains the data which will be through 6 Columns (excluding the first empty column) and 15 rows which will go into the DataGridView

NAME: JON
JOB: IT HELPER
PLACE: ADMIN
COMPANY: COMPANY NAME

Open in new window


Now the four last lines appears only once which will go to its each TextBox
Is it spaces between the columns in the text file or tabs?
Tabs, thats why i used "vbTab"
SOLUTION
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
It worked like a Charm!!! Thank you, i did use the example as shown and the result was:

   Private Sub OpenMenuItem_Click(sender As Object, e As EventArgs) Handles OpenMenuItem.Click
        Dim MyFile As String
        Open.Filter = "Resumo de Dose (*.csv)|*.csv|Todos os Arquivos (*.*)|*.*"
        Open.FilterIndex = 1
        If Open.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
            MyFile = Open.FileName
            Dim oInfile As New System.IO.StreamReader(MyFile)
            Dim tblInfile As New DataTable
            tblInfile.Columns.Add("Blank", GetType(String))
            tblInfile.Columns.Add("Event1", GetType(String))
            tblInfile.Columns.Add("Event2", GetType(String))
            tblInfile.Columns.Add("Event3", GetType(String))
            tblInfile.Columns.Add("Event4", GetType(String))
            tblInfile.Columns.Add("Event5", GetType(String))

            For i As Integer = 0 To 14
                Dim aryDataIn() = oInfile.ReadLine.Split(vbTab)
                tblInfile.Rows.Add(aryDataIn)
            Next


            DataLogGrid.DataSource = tblInfile

            txtName.Text = oInfile.ReadLine.Split(":")(1).Trim
            txtJob.Text = oInfile.ReadLine.Split(":")(1).Trim
            txtPlace.Text = oInfile.ReadLine.Split(":")(1).Trim
            txtCompany.Text = oInfile.ReadLine.Split(":")(1).Trim

            oInfile.Close()

        End If
    End Sub

Open in new window


But i got into a problem, in vb6 i had to add all Columns and Rows Headers programatically so it would only load the data into the Grid (In vb6 it was MsFlexGrid), i did the same into the DataGridView, added the columns and rows with its header, but here comes the problem, when i open the file into the app it Add new columns with the data and also empty my row headers, it doesn't insert.

What should i do?
Seeming this was a question in Visual Basic .Net and so was the solution I posted and as you verified it worked. As for you trying to implement this solution into VB6 you will need to open a new question in a VB6 thread because I am not well versed in VB6 to assist in it.
Oh no no sorry about that, what i meant is that i want to do that in Visual Basic.Net, i used VB6 as example of what i wanted to do in Visual Basic.Net.
What i'm trying to do now is:

Use the DataGridView to Read the data inside the DataTable "tblInfile", Because when i used:

DataLogGrid.DataSource = tblInfile

Open in new window


It does add new Rows and Empty my RowHeaders when it should just insert the data into the DataGridView, look what happens:

Before
User generated image
And After i load the File
User generated image

And really sorry for the incovenience, VB6 is off topic.
Two things, first what is the object type of "Open" as in Open.Filter and Open.ShowDialog and if it is a custom form you built can you post it. Second can you post the file that you are using to read in so I can test with.
Okay let me post the whole code of the form.

Public Class DataLog
    Private Sub DataLogGrid_Layout(sender As Object, e As LayoutEventArgs) Handles DataLogGrid.Layout
        DataLogGrid.Rows.Add(15)
        DataLogGrid.Rows(0).HeaderCell.Value = "Utilizado ou Não"
        DataLogGrid.Rows(1).HeaderCell.Value = "Nível de Critério"
        DataLogGrid.Rows(2).HeaderCell.Value = "Nível Limiar"
        DataLogGrid.Rows(3).HeaderCell.Value = "Taxa de Troca"
        DataLogGrid.Rows(4).HeaderCell.Value = "Ponderação de Tempo"
        DataLogGrid.Rows(5).HeaderCell.Value = "115 dBRMS"
        DataLogGrid.Rows(6).HeaderCell.Value = "Excedeu 140 dB"
        DataLogGrid.Rows(7).HeaderCell.Value = "Data de Início(MM:DD)"
        DataLogGrid.Rows(8).HeaderCell.Value = "Hora de Início(HH:MM)"
        DataLogGrid.Rows(9).HeaderCell.Value = "Hora de Finalização(HH:MM)"
        DataLogGrid.Rows(10).HeaderCell.Value = "Tempo de Exposição(HH:MM)"
        DataLogGrid.Rows(11).HeaderCell.Value = "Valor de Dose (%)"
        DataLogGrid.Rows(12).HeaderCell.Value = "TWA (%Dose 8 Horas)"
        DataLogGrid.Rows(13).HeaderCell.Value = "Sinalização de Pico (HH:MM)"
        DataLogGrid.Rows(14).HeaderCell.Value = "Duração de Pico (MM:SS)"
    End Sub

    Private Sub SairToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SairToolStripMenuItem.Click
        Me.Close()
    End Sub

    Private Sub AbrirToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AbrirToolStripMenuItem.Click
        Dim MyFile As String
        Open.Filter = "Resumo de Dose (*.csv)|*.csv|Todos os Arquivos (*.*)|*.*"
        Open.FilterIndex = 1
        If Open.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
            MyFile = Open.FileName
            Dim oInfile As New System.IO.StreamReader(MyFile)
            Dim tblInfile As New DataTable
            tblInfile.Columns.Add("Blank", GetType(String))
            tblInfile.Columns.Add("Event1", GetType(String))
            tblInfile.Columns.Add("Event2", GetType(String))
            tblInfile.Columns.Add("Event3", GetType(String))
            tblInfile.Columns.Add("Event4", GetType(String))
            tblInfile.Columns.Add("Event5", GetType(String))

            For i As Integer = 0 To 14
                Dim aryDataIn() = oInfile.ReadLine.Split(vbTab)
                tblInfile.Rows.Add(aryDataIn)
            Next


            DataLogGrid.DataSource = tblInfile

            txtName.Text = oInfile.ReadLine.Split(":")(1).Trim
            txtJob.Text = oInfile.ReadLine.Split(":")(1).Trim
            txtPlace.Text = oInfile.ReadLine.Split(":")(1).Trim
            txtCompany.Text = oInfile.ReadLine.Split(":")(1).Trim

            oInfile.Close()

        End If
    End Sub
End Class

Open in new window



And also the example file. And really thank you for your patience.
GHE-2---AJUDANTE---JOSE.csv
I do not see the object type for "Open" as in Open.Filter and Open.ShowDialog? is it a form you created?
Open = OpenFileDialog

Just renamed it.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
That isn't a CSV, a csv has a header in the first line, what you have is an unstructured text file. A datatable has structured data. you can parse the text file and create structured data

Nome,Cargo, Setor,Empressa,Event1,Event2,Event3
JOSE CARLOS RONE FERREIRA ARAUJO,AJUDANTE,GHE 2 - MÃO DE OBRA DIRETA (OBRAS),MENDES JUNIOR TRADING E ENGENHARIA S.A.,85dB,80dB.

Open in new window

@David, In the question @Giulia states, "finding a way that i can import a txt file into the DataGridView"
@Fernando: I was referring to the sample data file.
@David, they are one and the same. Also from Wikipedia
The name "CSV" indicates the use of the comma to separate data fields. Nevertheless, the term "CSV" is widely used to refer a large family of formats, which differ in many ways. Some implementations allow or require single or double quotation marks around some or all fields; and some reserve the very first record as a header containing a list of field names. The character set being used is undefined: some applications require a Unicode byte order mark (BOM) to enforce Unicode interpretation (sometimes even a UTF-8 BOM.) Files that use the tab character instead of comma can be more precisely referred to as "TSV" for tab-separated values.

...

An optional header record (there is no sure way to detect whether it is present, so care is required when importing).
@Fernando Soto, it worked as it should! Thank you a lot!

And for the CSV thing, my company programmer made his DataLogger export its data from his Dosimeter as CSV, and it is only a text file separated by Tabbing,  @David is pretty right about the CSV, but what i wanted was only to import a normal text file tabbed into the DataGridView and it worked perfectly now!.

Thank you!
Worked as It should, Fernando Soto always doing his best.
Not a problem Giulia, glad to help.