Solved

Updating SQL table from datagridview

Posted on 2014-02-22
2
369 Views
Last Modified: 2014-02-23
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
0
Comment
Question by:SweetingA
2 Comments
 
LVL 96

Accepted Solution

by:
Bob Learned earned 500 total points
ID: 39880651
You are creating the SqlDataAdapter dynamically in code.  The SqlDataAdapter has the 4 CRUD operation commands--DeleteCommand, InsertCommand, SelectCommand, and UpdateCommand.  In order to do those operations, you need to assign an SqlCommand to the commands that you need to execute.

If your tables have a primary key, then you can use the SqlCommandBuilder to derive those commands dynamically.

SqlCommandBuilder Example
http://www.dotnetperls.com/sqlcommandbuilder

VB.NET example:

' Make sure table is prepared. (You won't need this.)
'
Prepare()

'
' Create a DataTable with 5 columns.
'
Dim table As New DataTable()
table.Columns.Add("Weight", GetType(Integer))
table.Columns.Add("Name", GetType(String))
table.Columns.Add("Breed", GetType(String))
table.Columns.Add("Size", GetType(Char))
table.Columns.Add("Date", GetType(DateTime))

'
' Add data to the DataTable. [This will be dynamically generated from your app.]
'
AddDogRow(table, 57, "Koko", "Shar Pei")
AddDogRow(table, 130, "Fido", "Bullmastiff")
AddDogRow(table, 92, "Alex", "Anatolian Shepherd Dog")
AddDogRow(table, 25, "Charles", "Cavalier King Charles Spaniel")
AddDogRow(table, 7, "Candy", "Yorkshire Terrier")

'
' Create new SqlConnection, SqlDataAdapter, and builder.
'
Using con = New SqlConnection(ConsoleApplication1.Properties.Settings.[Default].masterConnectionString)
	Using adapter = New SqlDataAdapter("SELECT * FROM Dogs2", con)
		Using New SqlCommandBuilder(adapter)
			'
			' Fill the DataAdapter with the values in the DataTable.
			'
			adapter.Fill(table)
			'
			' Open the connection to the SQL database.
			'
			con.Open()
			'
			' Insert the data table into the SQL database.
			'
			adapter.Update(table)
		End Using
	End Using
End Using

Open in new window

0
 

Author Closing Comment

by:SweetingA
ID: 39880901
Thankyou very much
0

Featured Post

MIM Survival Guide for Service Desk Managers

Major incidents can send mastered service desk processes into disorder. Systems and tools produce the data needed to resolve these incidents, but your challenge is getting that information to the right people fast. Check out the Survival Guide and begin bringing order to chaos.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Summary Displaying images in RichTextBox is a common requirement with limited solutions available. Pasting through clipboard or embedding into RTF content only support static images.  This article describes how to insert Windows control objects int…
In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…

685 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question