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.
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%
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, " ")
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
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) Loop End Using End Sub