首页 > 解决方案 > 当数据源是查询时,从 GridView 更新数据库

问题描述

我有 SQL QUERY: SELECT T_DATA_LOG.ID, T_DATA_LOG.SerialNumber, T_DATA_LOG.Note, T_EVENT.Name FROM T_DATA_LOG INNER JOIN T_EVENT ON T_DATA_LOG.ID_EVENT = T_EVENT.ID_EVENT;

表 T_DATA_EVENT 是 T_DATA_LOG 的事件目录

我需要更新 T_DATA_LOG。注意

我有这个程序。如果我直接使用电子表格,它可以工作。如果我使用查询(连接两个表)作为数据源,它就不起作用。

导入 System.Data.OleDb 公共类

Dim connetionString As String
Dim connection As OleDbConnection
Dim adapter As OleDbDataAdapter
Dim cmdBuilder As OleDbCommandBuilder
Dim ds As New DataSet
Dim changes As DataSet
Dim sql As String
Dim i As Int32

Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    'connetionString = "Data Source=Server_Name\SQLEXPRESS;Initial Catalog=Test;Trusted_Connection=True;"
    connetionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & "e:\tmp\KuKacka2.0.accdb;Persist Security Info=False;"
    connection = New OleDbConnection(connetionString)
    'sql = "Select * from D_DATA_LOG" - This is Work, but I need view data from T_EVENT

    sql = "SELECT T_DATA_LOG.ID, T_DATA_LOG.SerialNumber, T_DATA_LOG.Note, T_EVENT.Name FROM T_DATA_LOG INNER JOIN T_EVENT ON T_DATA_LOG.ID_EVENT = T_EVENT.ID_EVENT;"

    Try
        connection.Open()
        adapter = New OleDbDataAdapter(sql, connection)
        adapter.Fill(ds)
        DataGridView1.DataSource = ds.Tables(0)
        connection.Close()
    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try
End Sub



Private Sub DataGridView1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles DataGridView1.Click
    DataGridView1.DefaultCellStyle.SelectionBackColor = Color.Orange
End Sub

Private Sub Button2_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    'NOTE:  for this code to work, there must be a PK on the Table
    Try
        cmdBuilder = New OleDbCommandBuilder(adapter)
        changes = ds.GetChanges()
        If changes IsNot Nothing Then
            adapter.Update(changes)
        End If
        MsgBox("Changes Done")
    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try
End Sub

结束类

请给我一个建议。谢谢,大卫

标签: databasevb.net

解决方案


推荐阅读