0
votes

I am having trouble updating my database table with datagridview, I've read some thread about the problem and nothing seem to work in my case. Here is the code i use when populating the datagridview.

    Public Sub filldatagridserver(ByRef SQL As String, ByRef dg As DataGridView)
    Dim myDataset As DataSet = New DataSet
    myAdptr.SelectCommand = New SqlCommand(SQL, cnSQL)
    myAdptr.Fill(myDataset)

    dg.DataSource = myDataset.Tables(0)
    dg.AutoResizeColumns()

    myAdptr.Dispose()
    myDataset.Dispose()
    cnSQL.Close()

    End Sub

then i call this sub procedure with the ff code:

    Call filldatagridserver("SELECT * FROM tblQuarterCollection", dgQuarter)

i already used myAdptr.update but i keep getting error about table mapping etc. I also tried to quote out the dispose and close in that sub procedure but it still doesn't work.

is there anyway to properly populate the datagridview and update changes made to database. I think my last resort here would be looping thru each record the update the data according to current value in the datagridview. Please help.

3
It will be useful to see the code that calls the update, however if you destroy the adapter then you could not update anything with that - Steve
@steve this is what i use when doing the update. myAdptr.Update(myDataset, "tblPayMTC") - Hideki
Then add the name of the table also when you fill the dataset myAdptr.Fill(myDataset, "tblPayMTC"). Another important point to get the automatica update working is to have a primary key returned by the SELECT query. Did you have a primary key defined for your table? - Steve

3 Answers

0
votes

try this :

 Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim addcmd as new sqlcommand("INSERT INTO TableName VALUES(@col1,@col2)",YourConnectionString)
addcmd.parameters.addwithvalue("@col1",txtCol1.text)
addcmd.parameters.addwithvalue("@col2",txtCol2.text)
addcmd.executenonQuery


End Sub
0
votes

At last I managed to get my code working. I reviewed my database and reset the primary key and now it is working perfectly fine

0
votes

If you call the Update passing also the name of the table then you need to add that name when you fill initially the DataSet

myAdptr.SelectCommand = New SqlCommand(SQL, cnSQL)
myAdptr.Fill(myDataset, "tblPayMTC")

Another important point to get the automatic update working is to have a primary key returned by the SELECT query otherwise you need to write your own commands for the UpdateCommand, InsertCommand and DeleteCommand of the SqlDataAdapter instance.

The primary key is a column in your table tblQuarterCollection that uniquely identifies your records (usually an ID column with Identity set to true) but it can be also a group of columns that taken togheter works as Primary Key.
While it is not mandatory to have a column with this property set, it is highly advisable to have one