Vb.net – How to read txt files and display the results in a grid headers in Visual Basic 2010 express

datagridviewvb.net

This sounds so simple but I still can't find the answer to it after googling for a while. I have DataGridView on a form and it's called DataGridView1. I have two txt files (with single columns in each) data and I want to be able to display them as Row & Column headings (not as cell contents). For example, the two txt files are

  1. C:\temp\sObj.txt
  2. C:\temp\sQue.txt

Now:
sObj.txt contains data a, b & c in a single column &
sQue.txt contains data d, e & f in a single column.
Now what I want looks like:

a  b  c
d
e
f

Please help, I'm a beginner in programming & need this be done urgently.

Best Answer

As I already said in the comment section, you need a StreamReader to read the lines of your textfile. First of all you have to import the System.IO-namespace:

Import System.IO

So declare your StreamReader with the filepath to your textfile and read each line in it.

Then you have to add the text of your StreamReader as a Column to your DataGridView. The first parameter is the ColumnName, the second is the ColumnHeading:

Using reader As New StreamReader(@"YOURFILEPATHHERE")
    DataGridView1.Columns.Add(reader.ReadLine(),reader.ReadLine())
End Using

So now you have added your columns. Adding your Rows is easier:

Simply read the lines and add your Rows with your String (linetext) as the parameter:

DataGridView1.Rows.Add(reader.ReadLine())

It's pretty easy and you could have done that with minimal research.

Related Topic