Justin de Gois Justin de Gois - 9 months ago 99
Vb.net Question

How to read text file data and display in dataGridView with vb.net

I am new to reading from and writing to text files. I need to read the file and store the data of each cell in their respective arrays.

My text file has this character: "|" for column separators. The first column is string based,and the second and third columns are integer based. In the dataGridView there are four columns, the fourth column being the 2nd column percentage out of the total of both 2nd and 3rd columns.

Imports System.IO

Public Class Form1
Dim teamName As String = ""
Dim gamesWon As Integer = 0
Dim gamesLost As Integer = 0
Dim percentOfGamesWon As Double = (gamesWon + gamesLost) * gamesWon / 100%

Sub reader()
Dim textLine As String = ""
Dim SplitLine() As String
Using objReader As New StreamReader("C:\Users\WORK\Documents\text files\ALE.txt")
Do While objReader.Peek() <> -1
teamName = objReader.ReadLine()
gamesWon = objReader.ReadLine()
gamesLost = objReader.ReadLine()
textLine = teamName & "|" & gamesWon & "|" & gamesLost & "|" & percentOfGamesWon
SplitLine = Split(textLine, " ")
End Using
End Sub

Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
End Sub
End Class

Edit: I changed the code as I noticed I did not include the variables teamName, gamesWon, gamesLost, and percentOfGamesWon

I, however, still have an error. I cannot use the objReader.Readline() with neither gamesWon, and gamesLost.


You are trying to assign whole data lines to the individual variables. Instead, you need to split the value returned by ReadLine and convert the parts to the appropriate data type. Adding Option Strict On will also help (either at the top of the file or in the project compile options). You could also minimize the scope of your variables - they don't need to be declared at class level.

Sub reader()
    Using objReader As New StreamReader("C:\Users\WORK\Documents\text files\ALE.txt")
       Do While objReader.Peek() <> -1
          Dim line As String = objReader.ReadLine()
          Dim splitLine() As String = line.Split("|")
          Dim teamName As String = splitLine(0)
          Dim gamesWon As Integer = CInt(splitLine(1))
          Dim gamesLost As Integer = CInt(splitLine(2))
          Dim percentOfGamesWon As Double = gamesWon / (gamesWon + gamesLost) * 100
          Me.grdDisplay.Rows.Add(teamName, gamesWon, gamesLost, percentOfGamesWon)
   End Using
End Sub