我需要将.txt文件导入DataGridView,其中每列用空格分隔,但问题出在最后一列。最后一列包含不应被评估为“拆分”的空格(见下文)。
' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 SAT 0901 133000 1330 0002 002 003 000030 000000 00000000 000 00000C174BB 0000 This One
Private Sub ImpData(ByRef selectedFile As String)
Dim dt As New DataTable
For d = 1 To 14
dt.Columns.Add(d, GetType(String))
Next
Dim lines = IO.File.ReadAllLines(selectedFile)
Dim colCount = 14
For Each line In lines
Dim objFields = From field In line.Split(" "c)
Select field
Dim newRow = dt.Rows.Add()
newRow.ItemArray = objFields.ToArray()
Next
DataGridView1.DataSource = dt
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MetroButton1.Click
Dim selectedfile As String = ""
OpenFileDialog1.ShowDialog()
selectedfile = Path.GetFullPath(OpenFileDialog1.FileName)
txtTEST1.Text = selectedfile
ImpData(selectedfile)
End Sub
“输入数组比此表中的列数长。”是否因为每行的最后一列而引发错误。任何帮助将不胜感激。感谢
答案 0 :(得分:1)
以下代码对我来说是一种可行的解决方案。请注意,这是编码快速和脏。请仔细看看OOP,例如Object Oriented Programming By Example
Private Sub ImpData(ByRef selectedFile As String)
Dim dt As New DataTable
For d = 1 To 14
dt.Columns.Add(d, GetType(String))
Next
Dim lines = IO.File.ReadAllLines(selectedFile)
'-- Dim colCount = 16
For Each line In lines
Dim sLinePart1 As String = line.Substring(0, 77)
Dim sLinePart2 As String = line.Substring(78, line.Length - 78)
Dim objFields = From field In sLinePart1.Split(" "c) Select field
Dim newRow = dt.Rows.Add()
newRow.ItemArray = objFields.ToArray()
newRow(13) = sLinePart2
Next
DataGridView1.DataSource = dt
End Sub
请注意我的行中没有两个空格。
SAT 0901 133000 1330 0002 002 003 000030 000000 00000000 000 00000C174BB 0000 This One first
SAT 0901 133000 1330 0002 002 003 000030 000000 00000000 000 00000C174BB 0000 This One second