How To Populate DataGridview From a Text File Data In VB.Net
In this VB.NET Tutorial we will see How To Get Records From .txt File And Display The Values Into DataGridView Rows On Button Click Event Using Visual Basic.Net Programming Language And Visual Studio Editor.
Project Source Code:
Imports System.IO
Public Class TXT_TO_DGV
Dim table As New DataTable()
Private Sub TXT_TO_DGV_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' add columns to datatable
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"))
' set the datatable as datasource
DataGridView1.DataSource = table
End Sub
' button import
Private Sub ButtonImport_Click(sender As Object, e As EventArgs) Handles ButtonImport.Click
Dim lines() As String
Dim vals() As String
' get lines from the text file
lines = File.ReadAllLines("C:\Users\1BestCsharp\Desktop\table.txt")
For i As Integer = 0 To lines.Length - 1 Step +1 ' lines
vals = lines(i).ToString().Split("|")
Dim row(vals.Length - 1) As String
For j As Integer = 0 To vals.Length - 1 Step +1 ' columns
row(j) = vals(j).Trim()
Next j
table.Rows.Add(row)
Next i
End Sub
End Class
OutPut:
Download Projects Source Code