如何将两个Access表连接到一个DataGridView?

时间:2018-01-15 09:09:53

标签: vb.net visual-studio ms-access datagridview

我希望用户能够在datagridview(dgvDynamic)中查看故障单(tblTickets)和订单(tblOrders)。

然而,我在单击“btnDisplay”时收到错误信息,指出FROM语句的格式错误。我不确定如何实际加入这两个表,以便在满足条件时,记录将出现在表中。

以下是代码:

Imports System.Data.OleDb
    Public Class frmViewTables
        Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & Application.StartupPath & "\SAC1 Database.mdb"
        Dim MyConn As OleDbConnection
        Dim da As OleDbDataAdapter
        Dim ds As DataSet
        Dim tables As DataTableCollection
        Dim source1 As New BindingSource
        Dim dt As DataTable

        Private Sub btnDisplayDataGrid_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplayDataGrid.Click

            Dim source1 As New BindingSource
            Dim ds = New DataSet
            Dim tables = ds.Tables
            Dim cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & Application.StartupPath & "\SAC1 Database.mdb")
            Dim da As OleDbDataAdapter = New OleDbDataAdapter()
            Dim cmd As New OleDbCommand("Select * from [tblOrders] inner join [tblTickets] where Username = @username", cn)
            cmd.Parameters.Add("@username", OleDbType.VarChar, 255).Value = frmLogin.SuccessfulLoginUsername
            da.SelectCommand = cmd
            da.Fill(ds, "tblOrders")
            Dim view As New DataView(tables(0))
            source1.DataSource = view
            dgvDynamic.DataSource = view
    End Sub
    End Class

谢谢。

1 个答案:

答案 0 :(得分:0)

查看错误是在查询语法中。内部联接应该指定两个表的连接列,如下所示。

Dim cmd As New OleDbCommand("Select * from [tblOrders] inner join [tblTickets] ON [tblOrders].OrderID=[tblTickets].OrderID where Username = @username", cn)
  • 我假设父表的tblOrders主键是OrderID,tblTickets与外键具有相同的名称列。纠正上述查询中的“ON [tblOrders].OrderID=[tblTickets].OrderID”并反馈它是否有效。如果没有,则分享两个表格列信息。

-Thanks