我正在为我遇到的问题寻求帮助。我在一个文件夹中有多个文本文件。该文件夹中可以包含“无限”数量的文本文件,尽管通常有 2-150 个文件 http://gyazo.com/5f314d1ca374abf9f813914609dd931d(此 + 下面的图像,由于缺乏声誉而无法嵌入)
然后,每个文件在其中包含“无限”(尽管通常为 0-20 行)数量的数据。第 1 行是“测试编号”,第 2 行是“测试结果”——如上图所示
我的数据网格视图中有 3 列(用户名、测试编号、测试结果) - 如上图所示
在下面运行我的代码时;添加到数据网格视图的第一条记录完美运行,但第二条(或第一条之后的任何记录)出现错误:http: //gyazo.com/0d492b97d918853e62c55ee314f3f181(图像)或错误消息:
“System.InvalidOperationException:集合已经属于 DataGridView 控件。此操作不再有效。在 System.Windows.Forms.DataGridViewCellCollection.Add(DataGridViewCelldataGridViewCell) 在 SpellingBee.TeacherMultiResults.TeacherMultiResults_Load(Object sender, EventArgs e)”
此错误发生在DGVRow.Cells.Add(DGVCell) 'add cell to row
我不想做的一件事是更改我的任何文本文件/文件夹结构,即使我知道它目前的存储效率低下。
我该如何解决这个错误?我正在使用 VB.net (Visual Studios 2013)
如果您需要更多信息,请询问
非常感谢。
Imports System.Windows.Forms
Imports System.IO
Public Class TeacherMultiResults
Dim AmountOfFiles
Dim LineCount As Integer = 0
Dim FileName As IO.FileInfo
Dim DGVRow As New DataGridViewRow
Dim DGVCell As DataGridViewCell
Dim Username As String = ""
Dim TestNumber As Integer = 0
Dim TestResult As Integer = 0
Private Sub TeacherMultiResults_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim directory As New IO.DirectoryInfo(LoadForm.CurrentDirectory & "\UserResults\") 'selects directory
Dim FileNames As IO.FileInfo() = directory.GetFiles()
Dim Files As IO.FileInfo
For Each Files In FileNames 'list the names of all files in the specified directory
Username = Files.ToString
Username = (Username.Substring(0, Username.Length - 4)) 'removes the .txt from the name
Try
LineCount = File.ReadAllLines(LoadForm.CurrentDirectory & "\UserResults\" & Username & ".txt").Length 'amount of lines in file
If LineCount > 1 Then
Dim Information As New System.IO.StreamReader(LoadForm.CurrentDirectory & "\UserResults\" & Username & ".txt") 'opens file
LineCount = LineCount / 2 'halfs line count
For i = 0 To LineCount - 1
TestNumber = Information.ReadLine() 'reads line to variable
TestResult = Information.ReadLine() 'reads line to variable
i = i + 1 'adds one to i
DGVCell = New DataGridViewTextBoxCell 'create a new DGV text box cell
DGVCell.Value = Username 'add value to DGV text box cell
DGVRow.Cells.Add(DGVCell) 'add cell to row
DGVCell = New DataGridViewTextBoxCell 'create a new DGV text box cell
DGVCell.Value = TestNumber 'add value to DGV text box cell
DGVRow.Cells.Add(DGVCell) 'add cell to row
DGVCell = New DataGridViewTextBoxCell 'create a new DGV text box cell
DGVCell.Value = TestResult 'add value to DGV text box cell
DGVRow.Cells.Add(DGVCell) 'add cell to row
DGV_MultiResults.Rows.Add(DGVRow) 'add row to DGV
Next
Information.Close() 'Close read
End If
Catch ex As Exception 'if file won't read
MsgBox(ex.ToString) 'show error
Exit Try
End Try 'end of try
Next 'end of files
End Sub
我希望有人可以帮助我解决这个问题,我知道修复很可能很简单,尽管我似乎无法找到错误的解决方案!
非常感谢,托比。