![](/img/trans.png)
[英]How to export data in a DataGridView to a text file in VB.NET
[英]How to read text file data and display in dataGridView with vb.net
我是阅读和写入文本文件的新手。 我需要读取文件并将每个单元格的数据存储在各自的数组中。
我的文本文件具有以下字符:“ |” 用于列分隔符。 第一列基于字符串,第二列和第三列基于整数。 在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
但是,我仍然有一个错误。 我不能将objReader.Readline()与gameWon和gamesLost一起使用。
您正在尝试将整个数据行分配给各个变量。 相反,您需要拆分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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.