You must be getting this error if you have not added columns before inserting the rows into the
DataGridView1
above in your code.
Given you are adding data to grid row by row, you need to define columns before doing it.
2 options:
1. Add the columns before adding the rows. Add columns in a sequence you plan to add data in
2. Assign datatable to the grid as datasource to bind
Example for your above code to add columns:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
DataGridView1.ColumnCount = 3
DataGridView1.Columns(0).Name = "Product ID"
DataGridView1.Columns(1).Name = "Product Name"
DataGridView1.Columns(2).Name = "Product_Price"
Dim row As String() = New String() {"1", "Product 1", "1000"}
DataGridView1.Rows.Add(row)
row = New String() {"2", "Product 2", "2000"}
DataGridView1.Rows.Add(row)
row = New String() {"3", "Product 3", "3000"}
DataGridView1.Rows.Add(row)
row = New String() {"4", "Product 4", "4000"}
DataGridView1.Rows.Add(row)
End Sub
More details, refer:
DataGridView.Columns Property (System.Windows.Forms) | Microsoft Docs[
^]