Link to home
Start Free TrialLog in
Avatar of SweetingA
SweetingA

asked on

Updating SQL table from datagridview

I have an SQL query linked to a datagridview.

I can update / delete data etc using single sql statements bt when i try to do it by simply put data in the datagrid view table i get the following error.

"Update requires valid UpdateCommand when passed datarows with modified data rows"

This is what fails on the form close event.......

Imports System.Data.SqlClient

Public Class Form1
    ' Shared variables
    Dim con As SqlConnection = New SqlConnection("Server=.\SQLEXPRESS;Database=OEE;USER Id=Alan Sweeting;Trusted_Connection=True")
    Dim cmd As SqlCommand
    Dim myDA As SqlDataAdapter
    Dim myDataSet As DataSet

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

        'Binding database table to DataGridView
        cmd = New SqlCommand("Select * FROM qry_Stops", con)
        If con.State = ConnectionState.Closed Then con.Open()
        myDA = New SqlDataAdapter(cmd)
        myDataSet = New DataSet()
        myDA.Fill(myDataSet, "qry_Stops")
        DataGridView1.DataSource = myDataSet.Tables("qry_Stops").DefaultView

    End Sub

Private Sub Form1_FormClosed(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles MyBase.FormClosed
        'update records
        Me.Validate()
        myDA.Update(myDataSet.Tables("qry_Stops"))
        myDataSet.AcceptChanges()
        con.Close()
        con = Nothing
    End Sub
End Class

I tried seperately with a simple update line and that works fine when i know what is updated but in the case i don;t know what is going to be changed and on which row.

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click

        'update record
        cmd = New SqlCommand("Update qry_Stops Set [DowntimeCode]=1 Where [DowntimeDescription]='Mech'", con)
        If con.State = ConnectionState.Closed Then con.Open()
        cmd.ExecuteNonQuery()
        ShowStops() 'Rebinding to DataGridView and view result

    End Sub

Public Sub ShowStops()

        'Binding database query to DataGridView
        cmd = New SqlCommand("Select * FROM qry_Stops", con)
        If con.State = ConnectionState.Closed Then con.Open()
        myDA = New SqlDataAdapter(cmd)
        myDataSet = New DataSet()
        myDA.Fill(myDataSet, "qry_Stops")
        DataGridView1.DataSource = myDataSet.Tables("qry_Stops").DefaultView

    End Sub

I am a total novice so please don't pass me to another link, i need someone to explain to me what i am doing wrong.

Thankyou
ASKER CERTIFIED SOLUTION
Avatar of Bob Learned
Bob Learned
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of SweetingA
SweetingA

ASKER

Thankyou very much