שתף באמצעות


How to read a text file line by line in DataGrid View

Question

Friday, March 6, 2015 7:11 PM

I'm completely new to VB.net and have been given a homework assignment. I need to be able to read certain lines and display them in a DataGridView. I have been able to link my .txt file to the DGV however it reads the whole file as opposed to the specific line. I have 4 buttons: btn1, btn2, btn3, btn4. I want each button to show the respective lines in the text file. After researching on-line for the past week I'm still stuck. If anyone could help me I would really appreciate it.

Text File ("database.txt")

**c1   c2   c3  ** <Coloumn Names

one 1-1 1-2

 two 2-2 2-3

 three 3-2 3-3

 four 4-2 4-3

Public Class Form1

    Private Sub btn1_Click(sender As Object, e As EventArgs) Handles btn1.Click

        Dim lines = (From line In IO.File.ReadLines("products.txt") _
                    Select line.Split(CChar(vbTab))).ToArray
        For x As Integer = 0 To lines(0).GetUpperBound(0)
            DataGridView1.Columns.Add(lines(0)(x), lines(0)(x))
        Next
        For x As Integer = 1 To lines.GetUpperBound(0)
            DataGridView1.Rows.Add(lines(x))
        Next
    End Sub

All replies (4)

Friday, March 6, 2015 8:47 PM ✅Answered

Hi

Here is one way to do it. Obviously, the file path needs to be adjusted. This example is NOT scalable.

' suggest you use these option settings
Option Strict On
Option Infer Off
Option Explicit On
Public Class Form1
    Dim DataFilePath As String = Application.StartupPath & "\Products.txt"
    Private Sub Btn1_Click(sender As Object, e As EventArgs) Handles btn1.Click, btn2.Click, btn3.Click, btn4.Click

        Dim lines() As String = IO.File.ReadAllLines(DataFilePath)

        ' add columns only if DGV has none
        If DataGridView1.Columns.Count = 0 Then
            For Each line As String In lines
                Dim a() As String = Split(line, vbTab)
                DataGridView1.Columns.Add(a(0), a(0))
            Next
        End If

        Dim b As Button = DirectCast(sender, Button)
        Select Case b.Name
            Case "btn1"
                DataGridView1.Rows.Add(Split(lines(0), vbTab))
            Case "btn2"
                DataGridView1.Rows.Add(Split(lines(1), vbTab))
            Case "btn3"
                DataGridView1.Rows.Add(Split(lines(2), vbTab))
            Case "btn4"
                DataGridView1.Rows.Add(Split(lines(3), vbTab))

        End Select
    End Sub
End Class

Regards Les, Livingston, Scotland


Friday, March 6, 2015 9:00 PM ✅Answered

You display the below.

So the datagridview is suppose to have column names of c1, c2 and c3. Then you show "one 1-1 1-2" which I don't know what that is. c1 should have the word one under it and c2 should have 1-1 under it and c3 should have 1-2 under it?

Why don't you copy and paste the text from the text file you want to use into a code block so we can see the text in it. And you don't need to select a language in the code block just copy and paste the text into it then preview and insert the code block.

c1   c2   c3    <Coloumn Names

one 1-1 1-2

two 2-2 2-3

three 3-2 3-3

four 4-2 4-3

La vida loca


Saturday, March 7, 2015 12:15 AM ✅Answered

How about this?  Just add a Button, DataGridView, and OpenFileDialog1

Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Linq
Imports System.Text
Imports System.Windows.Forms

Namespace WindowsFormsApplication1
    
    Public Class Form1
        Inherits Form
        
        Public Sub New()
            MyBase.New
            InitializeComponent
        End Sub
        
        Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs)
            If (openFileDialog1.ShowDialog <> DialogResult.Cancel) Then
                Dim sLine As String = ""
                Try 
                    'Pass the file you selected with the OpenFileDialog control to
                    'the StreamReader Constructor.
                    Dim FileStream As System.IO.StreamReader = New System.IO.StreamReader(openFileDialog1.FileName)
                    'You must set the value to false when you are programatically adding rows to
                    'a DataGridView.  If you need to allow the user to add rows, you
                    'can set the value back to true after you have populated the DataGridView
                    dataGridView1.AllowUserToAddRows = false
                    'Read the first line of the text file
                    sLine = FileStream.ReadLine
                    'The Split Command splits a string into an array, based on the delimiter you pass.
                    'I chose to use a semi-colon for the text delimiter.
                    'Any character can be used as a delimeter in the split command.
                    Dim s() As String = sLine.Split(Microsoft.VisualBasic.ChrW(59))
                    'In this example, I placed the field names in the first row.
                    'The for loop below is used to create the columns and use the text values in
                    'the first row for the column headings.
                    Dim i As Integer = 0
                    Do While (i  _
                                <= (s.Count - 1))
                        Dim colHold As DataGridViewColumn = New DataGridViewTextBoxColumn
                        colHold.Name = ("col" + System.Convert.ToString(i))
                        colHold.HeaderText = s(i).ToString
                        dataGridView1.Columns.Add(colHold)
                        i = (i + 1)
                    Loop
                    'Read the next line in the text file in order to pass it to the
                    'while loop below
                    sLine = FileStream.ReadLine
                    'The while loop reads each line of text.
                    
                    While (Not (sLine) Is Nothing)
                        'Adds a new row to the DataGridView for each line of text.
                        dataGridView1.Rows.Add
                        'This for loop loops through the array in order to retrieve each
                        'line of text.
                        Dim i As Integer = 0
                        Do While (i  _
                                    <= (s.Count - 1))
                            'Splits each line in the text file into a string array
                            s = sLine.Split(Microsoft.VisualBasic.ChrW(59))
                            'Sets the value of the cell to the value of the text retreived from the text file.
                            dataGridView1.Rows((dataGridView1.Rows.Count - 1)).Cells(i).Value = s(i).ToString
                            i = (i + 1)
                        Loop
                        sLine = FileStream.ReadLine
                        
                    End While
                    'Close the selected text file.
                    FileStream.Close
                Catch err As Exception
                    'Display any errors in a Message Box.
                    System.Windows.Forms.MessageBox.Show(("Error:  " + err.Message), "Program Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                End Try
            End If
        End Sub
    End Class
End Namespace

Knowledge is the only thing that I can give you, and still retain, and we are both better off for it.


Saturday, March 7, 2015 7:57 AM

Lorr,

If it is homework you have to tell your teacher how you did it. 

Telling, I'm asked some persons in a forum and they gave me the code is not such a good way to get the next semester.

But you can of course tell that they gave you some hints, one of those is to look first in the way your Text File is organized. Maybe it is a kind of common separated file and then there are very easy ways to do your assignment.

Then you can start searching on Internet with for instance a search text Comma Separated Text File and DataGridView and Visual Basic

You will get some results and you can implement those in your homework. 

You will see that your teacher likes that way better than just copy and past the code some guys in a forum did for you.

Success
Cor