如何读取文本文件数据并使用vb.net在dataGridView中显示

时间:2016-09-12 17:35:46

标签: vb.net datagridview

我不熟悉阅读和写入文本文件。我需要读取文件并将每个单元的数据存储在各自的数组中。

我的文字文件有这个字符:“|”用于列分隔符。第一列是基于字符串的,第二列和第三列是基于整数的。在dataGridView中有四列,第四列是第二列和第三列总和中的第二列百分比。

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, " ")
              Me.grdDisplay.Rows.Add(SplitLine)
          Loop
       End Using
    End Sub

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

编辑:我更改了代码,因为我注意到我没有包含变量teamName,gamesWon,gamesLost和percentOfGamesWon

然而,我仍然有错误。我不能将gamejon和gamesLost使用objReader.Readline()。

1 个答案:

答案 0 :(得分:3)

您正在尝试将整个数据行分配给各个变量。相反,您需要拆分ReadLine返回的值,并将部件转换为适当的数据类型。添加Option Strict On也会有所帮助(无论是在文件顶部还是在项目编译选项中)。您还可以最小化变量的范围 - 它们不需要在类级别声明。

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
相关问题