Solved

Updating SQL table from datagridview

Posted on 2014-02-22
2
363 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

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Normally the drop down box control found in the .Net framework tools is able to select just one data and value at a time, which is displayed on the text area.   But what if you want to have multiple values to be selected in the drop down box? As …
In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

708 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now