[2005 Tip] Read Any Text File Into A DagaGridView
I started using VB 2005 Express yesterday. I wanted to populate an Unbound DataGridView from a text file. I couldn't find an easy way to do this...
I didn't want to use any data binding, databases, etc... Just wanted to read the file and put its contents into the DataGrideView.
The code assumes that the text file has rows of data and that the rows are divided into columns by commas. You don't have to know how many rows are in the file, and the rows don't have to have the same number of columns. Rows with fewer columns will simply have blank cells in the rightmost columns.
Code:
'Create a new TextFieldParser. The following code creates the
'TextFieldParser named MyReader and opens the file test.txt.
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\ColumnsTestFileRandomLength.txt")
'Define the TextField type and delimiter. The following code defines
'the TextFieldType property as Delimited and the delimiter as ",".
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
'Loop through the fields in the file. If any lines are corrupt, report an error
'and continue parsing. The following code loops through the file, creating a new
'array for each row and adding the fields to that array. The array is then added
'to the grid as a row. Any fields that are formatted incorrectly are reported.
'This code assumes there are no more than 20 fields in a row. You should change the
'ReDim r(20) to a bigger number if you need more columns (fields).
Dim currentRow As String()
Dim r() As String
Dim i As Integer
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
ReDim r(20) 'Start a new row array
i = -1
Dim currentField As String
For Each currentField In currentRow
i = i + 1 'Get ready for the next string in the array
r(i) = currentField 'add the next string to the array
Next
'Add more columns to the grid if needed
If grd1.ColumnCount < i + 1 Then grd1.ColumnCount = i + 1
grd1.Rows.Add(r)
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & "is not valid and will be skipped.")
End Try
End While
End Using
Re: [2005 Tip] Read Any Text File Into A DagaGridView
This forum is for asking questions. If you want to post code you've written for the benefit of others then that's what the CodeBank is for. I suggest that you ask a moderator to move this thread.