将数据保存到VB.net中DataGridView的文本文件中

时间:2016-06-16 12:13:54

标签: vb.net datagridview

我有一个包含6列的数据网格视图......

我需要按字符串

在一行中保存所有行和列

例如:

Table

当此表的数据保存到文本文件中时,它应如下所示:

John
0000000000
M
Mike
0000000000
M

编辑:

我尝试过这种事:

Dim name As String = DataGridView1.Rows(e.RowIndex).Cells(1).Value
Dim mobile As String = DataGridView1.Rows(e.RowIndex).Cells(2).Value
Dim gender As String = DataGridView1.Rows(e.RowIndex).Cells(3).Value

Dim fileName As String = CurDir() + "\Measures.txt"
Dim fileNum As Integer = FreeFile()

FileOpen(fileNum, fileName, OpenMode.Output)

PrintLine(fileNum, name)
PrintLine(fileNum, mobile)
PrintLine(fileNum, gender)

注意:数据应保存为字符串

感谢任何帮助,谢谢

2 个答案:

答案 0 :(得分:1)

这种方法可以让你接近。 您仍然需要进行验证等

Private Function exportDataGridView(filePath As String, dgv As DataGridView) As Boolean

    Using sw As New StreamWriter(filePath)

        For Each dr As DataGridViewRow In dgv.Rows
            For Each dc As DataGridViewCell In dr.Cells
                sw.WriteLine(dc.Value.ToString)
            Next
        Next
    End Using

    Return True

End Function

答案 1 :(得分:1)

此代码将使用循环遍历每个单元格。它也会忽略最后一行,即DataGirdView末尾的空行... 这是代码:

Using writer As New System.IO.StreamWriter(filePath) For row As Integer = 0 To DataGridView1.RowCount - 2 For col As Integer = 0 To DataGridView1.ColumnCount - 1 writer.WriteLine(DataGridView1.Rows(row).Cells(col).Value) Next Next End Using