RewForeN RewForeN - 5 months ago 46
Vb.net Question

Save data to text file from DataGridView in VB.net

I have a data grid view containing 6 columns...

I need to save all of the rows and columns on one line per String

For example:

Table

When this table's data is saved into the text file it should look like this:

John
0000000000
M
Mike
0000000000
M


EDIT:

I have tried this kind of thing:

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)


note: The data should be saved as a string

Any help would be appreciated, thanks

Answer

This method should get you close. You will still need to do validation etc

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