简体   繁体   中英

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:

表

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM