Read txt file to DataGridView in VB.NET

G_API
G_API used Ask the Experts™
on
Dear Experts,

I would like to read a txt file (test.txt) and load the data line by line to DataGridView in vb.net, The data in text file is something like this:
1,yes,100
2,no,50
3,no,60

So, the file needs to be read and split by (,) and then insert these lines to a DataGridView  that has three columns which are
number
agree
salary

The question is that, do you know how can I read the above data, split them and insert them to the DataGridView  in vb.net ?
Waiting for experts, and thanks in advance.
Regards
G_API
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Craig WagnerSoftware Architect

Commented:

string line;

using( StreamReader reader = new StreamReader( "TextFile1.csv" ) )
{
    while( ( line = reader.ReadLine() ) != null )
    {
        string[] parts = line.Split( ',' );
        dataGridView1.Rows.Add( parts );
    }
}

Open in new window

Author

Commented:
Hi, thanks for your reply,

How can I use it in VB.net as I have paste the code and gave me errors !
Software Architect
Commented:
It gave you errors because it's c#. I forgot you said VB.NET.

As an aside, you should probably spend some time learning what the code does and not rely on cutting-and-pasting from the internet in order to do your job or schoolwork. If you ever need to maintain or enhance the code in the future it would probably be beneficial to truly understand it.
Dim line As String
Dim reader As IO.StreamReader = Nothing

Try
    reader = New IO.StreamReader("TextFile1.csv")

    line = reader.ReadLine

    While Not line Is Nothing
        Dim parts As String() = line.Split(",")
        DataGridView1.Rows.Add(parts)

        line = reader.ReadLine
    End While
Finally
    If Not reader Is Nothing Then
        reader.Close()
    End If
End Try

Open in new window

Author

Commented:
Hi CraigWagner,
Its work correctly thanks. About understand and not copy and paste the code, off course, I need a working code so I can understand it line by line and customize as my needs.
Note: I am not a student and this is not a coursework :)
Regards

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial