2012-06-05 74 views
0

這讓我們看看你能幫助我。使用DataGridView進行MySQL更新

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 

有一個錯誤:

「System.InvalidOperationException」類型的未處理的異常出現在system.data.dll

其他信息:不支持對動態SQL生成的更新命令一個不返回任何關鍵列信息的SelectCommand。

此代碼的作品除非保存到MySQL數據庫沒有變化! 請幫我解決這個問題。

謝謝

邁克

回答

1

根據錯誤,你的表沒有主鍵 - 你怎麼能指望更新知道要更新的行(可能有重複)。