我的txt文件包含类似这样的数据
EN^FN^SN^GN^SQ^I48-14^000042^2014-11-19^15:13:45^2014-11-19^^
datagridview中的预期结果
EN FN SN GN SQ
I48-14 000042 2014-11-19 15:13:45 2014-11-19
在设计表单中,我有1个按钮来浏览文件目录,1个文本框来显示文件名,当然还有一个1 datagridview来显示转换结果 我有这个错误行
Me.DataGridView1.Rows.Add(SplitLine)
* No row can be added to a DataGridView control that does not have columns. Columns must be added first.
这是我没有成功的代码
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse.Click
Dim fName As String = ""
Dim Ex As OpenFileDialog = New OpenFileDialog()
'Ex.InitialDirectory = "c:\"
Ex.Filter = "(*.csv)|*.CSV|(*.txt)|*.txt"
Ex.FilterIndex = 2
Ex.RestoreDirectory = True
If (Ex.ShowDialog() = Windows.Forms.DialogResult.OK) Then
fName = Ex.FileName
End If
Me.TextBox1.Text = fName
Dim TextLine As String = ""
Dim SplitLine() As String
If System.IO.File.Exists(fName) = True Then
Dim objReader As New System.IO.StreamReader(fName)
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
SplitLine = Split(TextLine, "^")
Me.DataGridView1.Rows.Add(SplitLine)
Loop
Else
MsgBox("File Does Not Exist")
End If
End Sub
结束班
答案 0 :(得分:0)
此错误
Me.DataGridView1.Rows.Add(SplitLine)
* No row can be added to a DataGridView control that does not have columns. Columns must be added first.
当您的datagridview没有任何列时,会出现
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
SplitLine = Split(TextLine, "^")
Dim cl1 As New DataGridViewTextBoxColumn
With cl1
.HeaderText = "SomeRandaomeName"
.Name = "SomeRandaomeName"
.Width = 120
.ReadOnly = True
End With
Me.DataGridView1.Rows.Add(SplitLine)
Loop
它只是一个想法,您可以使用来自SplitLine的值更改SomeRandaomeName
答案 1 :(得分:0)
Dim fName As String = ""
Dim Ex As OpenFileDialog = New OpenFileDialog()
Ex.Filter = "(*.csv)|*.CSV|(*.txt)|*.txt"
Ex.FilterIndex = 2
Ex.RestoreDirectory = True
If (Ex.ShowDialog() = Windows.Forms.DialogResult.OK) Then
fName = Ex.FileName
End If
Me.TextBox1.Text = fName
Dim TextLine As String = ""
Dim SplitLine() As String
If System.IO.File.Exists(fName) = True Then
DataGridView1.Rows.Clear()
DataGridView1.Columns.Clear()
DataGridView1.Columns.Add("EN", "EN")
DataGridView1.Columns.Add("FN", "FN")
DataGridView1.Columns.Add("SN", "SN")
DataGridView1.Columns.Add("GN", "GN")
DataGridView1.Columns.Add("SQ", "SQ")
DataGridView1.Columns.Item("EN").Width = 120
DataGridView1.Columns.Item("FN").Width = 120
DataGridView1.Columns.Item("SN").Width = 120
DataGridView1.Columns.Item("GN").Width = 120
DataGridView1.Columns.Item("SQ").Width = 120
Dim objReader As New System.IO.StreamReader(fName)
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
SplitLine = Split(TextLine, "^")
Me.DataGridView1.Rows.Add(SplitLine)
Loop
Else
MsgBox("File Does Not Exist")
End If