Jack
Jack

Reputation: 157

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

Upvotes: 1

Views: 6178

Answers (2)

rrswa
rrswa

Reputation: 1050

This code will run through each cell using loops. It will also ignore the last row which is that empty row at the end of a DataGirdView... Here is the code:

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

Upvotes: 1

Andrew Mortimer
Andrew Mortimer

Reputation: 2370

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

Upvotes: 1

Related Questions