我对VB.net完全陌生并且已经完成了家庭作业。我需要能够读取某些行并在DataGridView中显示它们。我已经能够将我的.txt文件链接到DGV,但是它读取整个文件而不是特定的行。我有4个按钮:btn1,btn2,btn3,btn4。
我在表单中添加了一个新按钮,用于加载文本文件中的数据,将其解析为数据表,并将DataGridView1.DataSource设置为该DataTable。第二种方法然后创建一个新的数据表并从主数据表导入指定的行并在DGV中显示它。
我需要能够按下btn1并将数据显示在DGV中,如果按下btn2,数据将显示在它下面的行中等。
非常感谢任何帮助。
Private txtDataTable As DataTable
Private Sub loadFileBtn_Click(sender As Object, e As EventArgs) Handles
loadFileBtn.Click
txtDataTable = New DataTable("txtContents")
Dim txtContents As String()
Try
txtContents = IO.File.ReadAllLines("database.txt")
Catch ex As Exception
MsgBox(ex.Message)
Return
End Try
Dim txtLines As New List(Of String())
txtContents.ToList().ForEach(Sub(x) txtLines.Add(x.Split(CChar(vbTab))))
If txtLines.Count > 0 Then
txtLines.Item(0).ToList.ForEach(Sub(x) txtDataTable.Columns.Add(New DataColumn(x.ToString)))
txtLines.RemoveAt(0)
End If
If txtLines.Count > 0 Then
txtLines.ToList.ForEach(Sub(x) txtDataTable.Rows.Add(x.ToArray))
End If
DataGridView1.DataSource = txtDataTable
End Sub
Private Sub btn_Click(sender As Object, e As EventArgs) Handles btn1.Click,
btn2.Click, btn3.Click, btn4.Click
If txtDataTable Is Nothing Then Return
Dim rowIndex As Integer
If Integer.TryParse(DirectCast(sender, Button).Name.Replace("btn", String.Empty), rowIndex) Then
rowIndex -= 1
Else
Return
End If
Dim TempTable As DataTable = txtDataTable.Clone
If rowIndex < txtDataTable.Rows.Count Then
TempTable.ImportRow(txtDataTable.Rows(rowIndex))
End If
DataGridView1.DataSource = TempTable
End Sub
答案 0 :(得分:0)
我假设您的代码中这是一个TAB分隔的文本文件。如果您阅读这样的文件怎么办:
Using fileReader As New FileIO.TextFieldParser(PathToFileAsString)
fileReader.TextFieldType = FileIO.FieldType.Delimited
fileReader.SetDelimiters(vbTab)
While Not fileReader.EndOfData
Dim currentRow as String() = fileReader.ReadFields
For Each currentField As String In currentRow
'Have your way with it.
Next
End While
End Using