读csv文件没有显示任何内容?

时间:2014-03-03 10:22:58

标签: vb.net csv datagridview

我是visual basic的初学者,并尝试将csv文件导入datagridview

我使用的示例代码如下:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

  Using MyReader As New Microsoft.VisualBasic.
                FileIO.TextFieldParser("C:\test\text.txt")
    MyReader.TextFieldType = FileIO.FieldType.Delimited
    MyReader.SetDelimiters(",")
    Dim currentRow As String()
    While Not MyReader.EndOfData
        Application.DoEvents()
        Try
            currentRow = MyReader.ReadFields()
            With DataGridView1
                .ColumnCount = 2
                Dim row As String() = New String() {currentRow(0), currentRow(1)}
                .Rows.Add()
            End With
        Catch ex As Microsoft.VisualBasic.
                    FileIO.MalformedLineException
            MsgBox("Line " & ex.Message &
            "is not valid and will be skipped.")
        End Try
    End While
  End Using
End Sub

我使用的数据如下:

Date,distance
1,5
2,8
4,9
10,15

但是,在使用上面的代码导入datagridview文件后,我变为空白csv

输出如下:

enter image description here

1 个答案:

答案 0 :(得分:3)

使用以下代码

With DataGridView1
    ...
    .Rows.Add()
End With

通过调用Add而不带任何参数来创建一个空行。

你可能想打电话

.Rows.Add(row)