Home > Back-end >  How to add Row to DataGridView in Visual Basic (Visual Studio)
How to add Row to DataGridView in Visual Basic (Visual Studio)

Time:02-10

I want to be able to add a new row to my already existing DataGridView through the use of a button. How do I add this? (Using Visual Basic on Visual Studio)

Here is the Code Filling the DataGridView.

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Dim connection As New SqlConnection(PlaceHolder for String)
    Dim Table As New DataTable()
    
    Dim Adapter As New SqlDataAdapter("SELECT * FROM TrackMain$", connection)
   
    Adapter.Fill(Table)
    
    DataGridView1.DataSource = Table
    bind_data()

End Sub

CodePudding user response:

Since you are using a DataTable as a datasource, simply add a row to it before you bind

Dim toInsert = Table.NewRow()
Table.Rows.Add(toInsert)

If you are doing in a place other than where the initial binding is done, you should first retrieve the DataTable, then add, and rebind

Dim Table = DirectCast(DataGridView1.DataSource, DataTable)
Dim toInsert = Table.NewRow()
Table.Rows.Add(toInsert)
DataGridView1.DataSource = Table
bind_data()

CodePudding user response:

bind_data() method seems to come from enter image description here

To add a new row with data, you can use DataTable:

dt.Rows.Add(...)
  • Related