2016-09-20 168 views
3

我想更新我的datagridview,也是我的數據庫im新vb和我不知道什麼即時做錯了sombody可以幫助我嗎?更新datagridview和數據庫vb.net

Private Sub DataGridView_Booking_Update(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView_Booking.RowLeave 
    Try 
     con.Open() 
     Using cmd As New SqlCommand("UPDATE Tbl_booking SET Omschrijving = @Omschrijving, Jaar = @Jaar, Opmerking = @Opmerking ,Sortnr = @Sortnr)", con) 
      cmd.Parameters.Add("@Omschrijving", SqlDbType.VarChar) 
      cmd.Parameters.Add("@Jaar", SqlDbType.Int) 
      cmd.Parameters.Add("@Opmerking", SqlDbType.VarChar) 
      cmd.Parameters.Add("@Sortnr", SqlDbType.Int) 
      cmd.ExecuteNonQuery() 

     End Using 
    Catch ex As Exception 
     MessageBox.Show("Error while updating record on table..." & ex.Message, "Update Records") 
    Finally 
     con.Close() 
    End Try 
+0

你忘了你的參數設置的實際值。例如。 'cmd.Parameters.Add(「@ Omschrijving」,SqlDbType.VarChar).Value = dataGridView.Rows(e.RowIndex).Cells(e.ColumnIndex).Value'。此外,如果您提到任何錯誤,這將有所幫助。 –

+0

我得到錯誤「更新記錄在表...附近語法不正確時出錯」),如果得到通過,我得到錯誤「錯誤,同時在表上記錄...無法將參數值從字符串轉換爲Int32「 – Kevin

+0

查看SQL和錯誤消息。https://www.tutorialspoint.com/sql/sql-insert-query.htm – Plutonix

回答

-1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
    Try 
     Dim con As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\database1.accdb;Persist Security Info=False;") 
     con.Open() 
     Dim cmd As New OleDb.OleDbCommand("INSERT INTO table1(name,age,class) VALUES('John Legend','22','B.A Part 1')", con) 
     cmd.ExecuteNonQuery() 
     MsgBox("Record inserted successfully.") 
     con.Close() 
    Catch 
     MsgBox("Error Occured.") 
    End Try 
End Sub 

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click 
    Try 
     Dim con As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\database1.accdb;Persist Security Info=False;") 
     con.Open() 
     Dim cmd As New OleDb.OleDbCommand("update table1 set name='John DOE',age='23',class='12th' where id='1'", con) 
     cmd.ExecuteNonQuery() 
     MsgBox("Record Updated Successfully.") 
     con.Close() 
    Catch 
     MsgBox("Error Occured.") 
    End Try 
End Sub 

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click 
    Try 
     Dim con As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\database1.accdb;Persist Security Info=False;") 
     con.Open() 
     Dim cmd As New OleDb.OleDbCommand("Delete from table1 where name='John DOE'", con) 
     cmd.ExecuteNonQuery() 
     MsgBox("Record Deleted Successfully.") 
     con.Close() 
    Catch 
     MsgBox("Error Occured.") 
    End Try 
End Sub 

Private Sub DataGridView1_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged 

    Me.Validate() 
    Me.dbDataAdapter.Update(Me.dbdataset.Tables("MyTable")) 

    Me.dbDataSet.AcceptChanges() 

End Sub