Filling SQL Database Table from DataGridView

2.9k views Asked by At

Once again i am turning to you for help. I am a little stuck when trying to save data entered in a DataGridView back to the SQL table.

I have followed a number of posts but just cant seam to figure it out

I declare the following variables globally on the form

Dim SQLAdaptor As New SqlClient.SqlDataAdapter
Dim Con As New SqlClient.SqlConnection
Dim builder As SqlClient.SqlCommandBuilder

I call this when the form loads

Private Sub SetTicketList()

     Con.ConnectionString = CropTrackMod.strConn
     SQLAdaptor.SelectCommand = New SqlClient.SqlCommand("SELECT StockRef, Weight, EstimatedPrice, EstimatedPrice, DespatchedQuantity, EstimatedTransport, EstimatedLineTotal FROM TicketDetail", Con)
     builder = New SqlClient.SqlCommandBuilder(SQLAdaptor)
     Con.Open()

     Dim myTable As DataTable = New DataTable
     SQLAdaptor.Fill(myTable)

     dgvTicketDetail.DataSource = myTable   
End Sub

I call this when the user leaves a row on the data grid view which should save back to the sql table

Private Sub dgvTicketDetail_RowLeave
    ' at grid save'

    Dim myTable = CType(dgvTicketDetail.DataSource, DataTable)
    SQLAdaptor.Update(myTable)
End Sub

When the form is loaded the data grid view is populated with the correct columns so i think that the first part is ok. The problem comes when saving the data back. When I run it the first time there is no error message. When I try a second row I get the following error:

Update requires a valid InsertCommand when passed DataRow collection with new rows.

From what I can figure the problem is generated because there is no update command set on the data adaptor.

0

There are 0 answers