编写和读取DataGridView到文本文件

时间:2017-09-26 05:18:26

标签: vb.net datagridview streamreader streamwriter

我正在寻找一些有关如何使用文本文件中的数据填充DataGridView控件的帮助。列号是静态的,但行计数是动态的。我正在使用StreamWriter逐行创建文本文件。这是代码:

Private Sub btnSaveReport_Click(sender As Object, e As EventArgs) Handles btnSaveReport.Click
    Dim path As String = "c:\users\service5\desktop\ReportFile.txt"

    Using writer As New StreamWriter(path)

        For row As Integer = 0 To dgvLabor.RowCount - 2
            For col As Integer = 0 To dgvLabor.ColumnCount - 1
                writer.WriteLine("Labor" & "|" & dgvLabor.Rows(row).Cells(col).Value)
            Next
        Next

        writer.Close()
    End Using
End Sub

输出文件如下所示:

Labor|Mon 09/25/2017
Labor|Labor Time
Labor|11:42 PM
Labor|12:42 AM
Labor|23.00
Labor|20

使用StreamReader方法读取文本文件中的每一行并将其放在正确的列和行中时,我感到困惑。我使用“|”成功填充文本框分隔格式,但我不知道如何处理DataGridView代码。重新格式化我的StreamWriter方法以使文件以逗号分隔而不是“|”是明智的吗?分隔?

更新10/08/2017

好的,我让编写器按照我想要的方式格式化文本文件,StreamReader的工作率为95%。它成功填充了第一行的DataGridView,但它需要识别以“Labor”开头的每一行,并在该行中添加一个带有该数组的新行。以下是我试图读入DataGridView的文本示例。

Labor,Sun 10/08/2017,Labor Time,12:39 AM,12:39 AM,0.00,0
Labor,Mon 10/09/2017,Travel Time,12:39 AM,12:39 AM,0.00,0

以下是StreamReader代码:

Private Sub OpenFileDialog1_FileOk(sender As Object, e As CancelEventArgs) Handles OpenFileDialog1.FileOk

    Dim FileReader As StreamReader
    Dim prop(2) As String
    Dim path As String = OpenFileDialog1.FileName

    FileReader = New StreamReader(path, False)

    Do Until FileReader.EndOfStream

        prop = FileReader.ReadLine().Split(",")

    If String.Equals(prop(0), "Labor") Then

            Dim col(6) As String
            Dim index = dgvLabor.Rows.Add()
            col = FileReader.ReadLine().Split(",")
            dgvLabor.Rows(index).SetValues(col(1), col(2), col(3), col(4), col(5), col(6))

        End If
    Loop

    FileReader.Close()

End Sub

我遇到问题的部分是每次写入文本文件时以“Labor”开头的行数会有所不同,所以我认为我需要在If String.Equals方法中使用Do Until或Do While循环,但我无法正确理解语法。到目前为止,我已经尝试过这些并没有成功:

Do While String.Equals("Labor")
Do Until String.Equals(Not "Labor")
Do Until String.Equals(prop(0), "Labor")

有什么想法吗?

更新解决方案10/09/2017

在真正考虑我的代码正在做什么之后,我终于解决了这个问题。这简单愚蠢,证明我有多么过分思考一切。感谢您对我的帮助和耐心,jmcilhinney。希望这也可以帮助其他人。

        ElseIf String.Equals(prop(0), "Labor") Then

            dgvLabor.Rows.Add(prop(1), prop(2), prop(3), prop(4), prop(5), prop(6))

        End If

1 个答案:

答案 0 :(得分:0)

在真正考虑我的代码正在做什么之后,我终于解决了这个问题。这简单愚蠢,证明我有多么过分思考一切。感谢您对我的帮助和耐心,jmcilhinney。希望这也可以帮助其他人。

        ElseIf String.Equals(prop(0), "Labor") Then

            dgvLabor.Rows.Add(prop(1), prop(2), prop(3), prop(4), prop(5), prop(6))

        End If

此代码采用已经拆分的行,并将所需的数组对象插入到下一个可用行的单元格中。它只添加文本文档中以" Labor"

开头的行