VB.NET Export Datagridview Data To Text File

VB.NET - How To Export Datagridview Data To Text File In Visual Basic.Net


In This VB.NET Tutorial We Will See How To Export GridView Values To Txt File Using Visual Basic .NET Programming Language .


Project Source Code:

Imports System.IO
Public Class Datagridview_To_Text_File

    Dim table As New DataTable("Table")
    Private Sub Datagridview_To_Text_File_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        ' Add columns to your datatable, 
        ' with the name of the columns and their type 

        table.Columns.Add("Id", Type.GetType("System.Int32"))
        table.Columns.Add("First Name", Type.GetType("System.String"))
        table.Columns.Add("Last Name", Type.GetType("System.String"))
        table.Columns.Add("Age", Type.GetType("System.Int32"))

        ' Add rows to the datatable with some data
        table.Rows.Add(1, "XXXX", "YYYYY", 21)
        table.Rows.Add(2, "SSDD", "hGSQ", 33)
        table.Rows.Add(3, "fgfgd", "jgfdd", 53)
        table.Rows.Add(4, "rmfgh", "sdrgtyh", 19)
        table.Rows.Add(5, "hghfd", "ghjgdf", 36)
        table.Rows.Add(6, "cvvdfgh", "juyrfd", 63)

       'now set the datagridview datasource equals to your datatable name
        DataGridView1.DataSource = table

    End Sub

    Private Sub BTN_EXPORT_Click(sender As Object, e As EventArgs) Handles BTN_EXPORT.Click

        Dim writer As TextWriter = New StreamWriter("C:\folder\Text.txt")

        For i As Integer = 0 To DataGridView1.Rows.Count - 2 Step +1

            For j As Integer = 0 To DataGridView1.Columns.Count - 1 Step +1

                writer.Write(vbTab & DataGridView1.Rows(i).Cells(j).Value.ToString() & vbTab & "|")

            Next

            writer.WriteLine("")
            writer.WriteLine("---------------------------------------------")

        Next
        writer.Close()
        MessageBox.Show("Data Exported")

    End Sub
End Class

///////////////OUTPUT:

Vb.Net Datagridview Data To Txt File




Share this

Related Posts

Previous
Next Post »