如何将3个Ms-Access表中的信息加载到1个DataGridView?

时间:2018-02-21 11:26:59

标签: vb.net ms-access datagridview

我想从3个Ms-Access表中加载名称和一些信息 这是我的代码:

Sub loadnames()
    Try
        Dim dt As DataTable = New db_con().selectdata( _
              "SELECT famille1.ID, famille1.Article, famille1.quantité FROM famille1;")

        DataGridView1.Rows.Clear()
        For i As Integer = 0 To dt.Rows.Count - 1
            DataGridView1.Rows.Add(i + 1, dt.Rows(i)(0), dt.Rows(i)(1), dt.Rows(i)(2), dt.Rows(i)(3), dt.Rows(i)(4), dt.Rows(i)(5))
        Next
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try

End Sub

我想从表格中加载一些信息( famille2 & famille3 ),但只有一个代码加载到一个DataGridview。

2 个答案:

答案 0 :(得分:0)

非常粗糙,我肯定肯定有更好的方法可以做到这一点...但是...... :)这里是一种直接扩展代码的方法...

为每个查询创建一个数据表,并从每个查询填充数据网格。

Sub loadnames()
    Try
        Dim dt As DataTable = New db_con().selectdata( _
              "SELECT famille1.ID, famille1.Article, famille1.quantité FROM famille1;")

        Dim dt2 As DataTable = New db_con().selectdata( _
              "SELECT famille2.ID, famille2.Article, famille2.quantité FROM famille2;")

        Dim dt3 As DataTable = New db_con().selectdata( _
              "SELECT famille3.ID, famille3.Article, famille3.quantité FROM famille3;")

        DataGridView1.Rows.Clear()
        For i As Integer = 0 To dt.Rows.Count - 1
            DataGridView1.Rows.Add(i + 1, dt.Rows(i)(0), dt.Rows(i)(1), dt.Rows(i)(2), dt.Rows(i)(3), dt.Rows(i)(4), dt.Rows(i)(5))
        Next

        For i As Integer = 0 To dt2.Rows.Count - 1
            DataGridView1.Rows.Add(i + 1, dt2.Rows(i)(0), dt2.Rows(i)(1), dt2.Rows(i)(2), dt2.Rows(i)(3), dt2.Rows(i)(4), dt2.Rows(i)(5))
        Next

        For i As Integer = 0 To dt3.Rows.Count - 1
            DataGridView1.Rows.Add(i + 1, dt3.Rows(i)(0), dt3.Rows(i)(1), dt3.Rows(i)(2), dt3.Rows(i)(3), dt3.Rows(i)(4), dt3.Rows(i)(5))
        Next

    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try

End Sub

H个 鸡

答案 1 :(得分:0)

您的选择字符串应如下所示......

Dim strSQL As String = "SELECT ID, Article, quantité FROM famille1" &
                               "UNION ALL" &
                               "SELECT ID, Article, quantité FROM famille2" &
                               "UNION ALL" &
                               "SELECT ID, Article, quantité FROM famille3;"

然后当你得到你的DataTable

DataGridView1.DataSource = dt