I'm following a tutorial, which was going great, until I actually ran the project and got an error:

No row can be added to a DataGridView control that does not have columns. Columns must be added first.

this error occured at:

                Me.DataGridView1.Rows.Add(Splitline)

I've searched all over but can't find a solution. Is there something simple I'm missing?

My code.

Public Class Form1


    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

        Dim fName As String = ""
        OpenFileDialog1.InitialDirectory = "C:\"
        OpenFileDialog1.Filter = "Text Files (*.txt)|*.TXT"
        OpenFileDialog1.FilterIndex = 2
        OpenFileDialog1.RestoreDirectory = True
        If (OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK) Then
            fName = OpenFileDialog1.FileName

        End If
        Me.TextBox1.Text = fName
        Dim TextLine As String = ""
        Dim Splitline() As String

        If System.IO.File.Exists(fName) = True Then
            Dim objReader As New System.IO.StreamReader(fName)

            Do While objReader.Peek() <> -1
                TextLine = objReader.ReadLine()
                Splitline = Split(TextLine, ",")
                Me.DataGridView1.Rows.Add(Splitline)
            Loop
        Else
            MsgBox("File does not exist")

        End If
    End Sub

    Private Sub SaveGridDataInFile(ByRef fName As String)
        Dim I As Integer = 0
        Dim j As Integer = 0
        Dim cellvalue$
        Dim rowLine As String = ""

        Try
            Dim objWriter As New System.IO.StreamWriter(fName, True)
            For j = 0 To (DataGridView1.Rows.Count - 2)
                For I = 0 To (DataGridView1.Columns.Count - 1)

                    If Not TypeOf DataGridView1.CurrentRow.Cells.Item(I).Value Is DBNull Then
                        cellvalue = DataGridView1.Item(I, j).Value
                    Else
                        cellvalue = ""

                    End If
                    rowLine = rowLine + cellvalue + ","

                Next
                objWriter.WriteLine(rowLine)
                rowLine = ""

            Next
            objWriter.Close()
            MsgBox("text was written to file")

        Catch ex As Exception
            MessageBox.Show("Error occured." + ex.ToString)
        Finally
            FileClose(1)
        End Try


    End Sub

    Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
        SaveGridDataInFile(Me.TextBox1.Text)
    End Sub
End Class

Recommended Answers

All 2 Replies

Same exact thing is happening with other tutorials I use. It happened to this one too:

Public Class Form1
    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("c:\csvfile.txt")

            MyReader.TextFieldType = FileIO.FieldType.Delimited
            MyReader.SetDelimiters(",")

            Dim currentRow As String()
            While Not MyReader.EndOfData
                Try
                    currentRow = MyReader.ReadFields
                    With Me.dgvReport.Rows
                        .Add(currentRow)
                    End With
                Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
                    MsgBox("Line " & ex.Message & " is not valid and will be skipped")
                End Try
            End While
        End Using
    End Sub
End Class

Here's a simple sub, to use in your button click event handler, that will fill a datagridview from a .csv file. This sub accepts, the path of the file, the datagridview control, and an optional boolean, with a default value of false to use the first line as a header line and the columns will be set by those values. If set to true, the columns will be auto numbered.

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim fName As String = ""
    OpenFileDialog1.InitialDirectory = "C:\"
    OpenFileDialog1.Filter = "Text Files (*.txt)|*.TXT"
    OpenFileDialog1.FilterIndex = 2
    OpenFileDialog1.RestoreDirectory = True
    If (OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK) Then
        fName = OpenFileDialog1.FileName
    End If
    Me.TextBox1.Text = fName
    GetData(fname,DataGridView1, True)
End Sub


Private Sub GetData(ByVal Path As String, ByRef DG As DataGridView, Optional ByVal NoHeader As Boolean = False)
    Dim Fields() As String
    Dim Start As Integer = 1
    If NoHeader Then Start = 0
    If Not File.Exists(Path) Then
        Return
    End If
    Dim Lines() As String = File.ReadAllLines(Path)
    Lines(0) = Lines(0).Replace(Chr(34), "")
    Fields = Lines(0).Split(",")
    If NoHeader Then
        For I = 1 To Fields.Count - 1
            Fields(I) = Str(I)
        Next
    End If
    For Each Header As String In Fields
        DG.Columns.Add(Header, Header)
    Next
    For I = Start To Lines.Count - 1
        Lines(I) = Lines(I).Replace(Chr(34), "")
        Fields = Lines(I).Split(",")
        DG.Rows.Add(Fields)
    Next
End Sub
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.