mike
mike

Reputation: 201

MySQL Update using DataGridView

This goes to the genius out there let's see if YOU can help me.

Imports System
Imports System.Data

' Version 6.5.4.0 Runtime v2.0.50727
Imports MySql.Data.MySqlClient

Public Class MainForm

  ' Config - Main. 
  Private db_host As String = ""
  Private db_username As String = ""
  Private db_userpass As String = ""
  Private db_catalog As String = ""
  Private db_port As String = "3306"

  ' Config - Specific Table.
  Private db_specific_table As String = "SF6SETUP"

  ' Config - Other.
  Private DS As DataSet
  Private DA As MySqlDataAdapter
  Private BS As BindingSource

  ' ***
  '
  ' ***
  Private Sub My_Init()

    Dim conn As String = "Data Source = " & db_host & ";Initial Catalog=" & db_catalog & "; uid=" & db_username & ";password=" & db_userpass
    Dim myConnection As New MySqlConnection(conn)
    Dim cmd As String = "SELECT * FROM " & db_specific_table

    DA = New MySqlDataAdapter(cmd, myConnection)
    ' This line of code to generate update commands automatically.
    ' This update method of would not work without this line of code. 
    Dim MySQLCommandBuilder As New MySqlCommandBuilder(DA)

    myConnection.Open()

    DS = New DataSet()
    DA.Fill(DS, "MyTable")

    BS = New BindingSource
    BS.DataSource = DS.Tables(0)

    Dim BN As BindingNavigator = New BindingNavigator()
    BN.BindingSource = BS
    DataGridView.DataSource = BS

  End Sub

  ' ***
  '
  ' ***
  Private Sub MainForm_Load(sender As Object, e As System.EventArgs) Handles Me.Load

    My_Init()

  End Sub

  Private Sub DataGridView_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles DataGridView.KeyPress
    BS.EndEdit()
    DA.Update(DS, "MyTable")
  End Sub
End Class

There is an error:

An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll

Additional information: Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.

This code works EXCEPT no changes saved to MySQLDatabase!!! Please, help me solve this.

Thank you,

Mike

Upvotes: 0

Views: 1501

Answers (1)

Nikola Bogdanović
Nikola Bogdanović

Reputation: 3213

According to the error, your table does not have a primary key - how do you expect update to know which row to update (there could be duplicates).

Upvotes: 1

Related Questions