【问题标题】:How to read text file data and display in dataGridView with vb.net如何使用 vb.net 读取文本文件数据并在 dataGridView 中显示
【发布时间】:2017-01-20 05:06:24
【问题描述】:

我是读取和写入文本文件的新手。我需要读取文件并将每个单元格的数据存储在各自的数组中。

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

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() 与 gamesWon 和 gamesLost 一起使用。

【问题讨论】:

  • OleDB 可以将其读入 DataTable,因此您可以将其绑定到您的 DGV。请阅读How to Ask,也请阅读Tour...还有很多细节缺失
  • 我显然不擅长表达我的问题,我知道。我没有使用过 OleDB。我应该获取数据并将其显示在 DGV 中并手动执行此操作。
  • 也许一些代码显示您尝试过的内容以及您如何通过问题描述进行操作会有所帮助。请阅读How to Ask,也请阅读Tour
  • @Plutonix 添加了 vb 代码。
  • 膨胀了,现在有问题吗?它有效吗?有错误吗?如果有,那是什么?问题是什么?

标签: vb.net datagridview


【解决方案1】:

您正在尝试将整个数据行分配给各个变量。相反,您需要拆分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

【讨论】:

  • 有效!谢谢!如果我按 percentOfGamesWon 的降序对 DGV 进行排序,我会怎么做?
  • 老实说,我不确定如何按 percentOfGamesWon 实现排序
  • 我已经用grdDisplay.Sort(grdDisplay.Columns(3), ListSortDirection.Descending)排序了
猜你喜欢
  • 1970-01-01
  • 2011-11-07
  • 2013-03-21
  • 1970-01-01
  • 2014-04-13
  • 1970-01-01
  • 1970-01-01
  • 2020-05-02
  • 1970-01-01
相关资源
最近更新 更多