如何根据 combobox1 中的 *selected* 访问数据库表填充 combobox2,而无需为 vb.net 中的每个表编写 If 语句

How to populate combobox2 depending on *selected* access database table in combobox1 without writing If statements for each table in vb.net

提问人:Kudzanai Victor 提问时间:11/8/2023 最后编辑:DaiKudzanai Victor 更新时间:11/8/2023 访问量:31

问:

我想提示用户从 combobox1 中选择一个工具名称,然后自动输出,combobox2 会填充该特定工具的工具描述和大小,这是所选表中的一列。

目前我一直在使用以下代码,但是当我想更新数据库并添加另一个表时,问题就来了。这意味着还要在应用程序中添加代码。我希望应用程序能够检测到已添加新的工具表并自动显示,而无需再次编码

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    ' ADDING TABLE NAMES TO COMBOBOX 1 (TOOL NAME)
    con.Open()
    Dim schemaTable As DataTable = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, New Object() {Nothing, Nothing, Nothing, "TABLE"})
    For Each dr As DataRow In schemaTable.Rows
        Combobox1.Items.Add(dr.Item("TABLE_NAME"))
    Next

End Sub

Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles Combobox1.SelectedIndexChanged

    'FILLING COMBOBOX 2 (TOOL DESCRIPTION AND SIZE) DEPENDING ON SELECTION IN COMBOBOX 1 (TOOL NAME)

    If Combobox1.SelectedIndex = 1 Then

        Combobox2.Text = ""
        con.Open()
        Combobox2.Items.Clear()

        Dim dr As OleDbDataReader
        Dim cmd As New OleDbCommand

        cmd.CommandText = "Select * from 14_POUND_HAMMER"
        cmd.Connection = con

        dr = cmd.ExecuteReader

        While dr.Read
            Combobox2.Items.Add(dr.GetString(1))
        End While

        dr.Close()
        con.Close()

    ElseIf Combobox1.SelectedIndex = 2 Then

        Combobox2.Text = ""
        con.Open()
        Combobox2.Items.Clear()

        Dim dr As OleDbDataReader
        Dim cmd As New OleDbCommand

        cmd.CommandText = "Select * from 3_QUARTER_IMPACT_WRENCH"
        cmd.Connection = con

        dr = cmd.ExecuteReader

        While dr.Read
            Combobox2.Items.Add(dr.GetString(0))
        End While

        dr.Close()
        con.Close()

    ElseIf Combobox1.SelectedIndex = 3 Then

        Combobox2.Text = ""
        con.Open()
        Combobox2.Items.Clear()

        Dim dr As OleDbDataReader
        Dim cmd As New OleDbCommand
        cmd.CommandText = "Select * from ABRASIVE_CUT_OFF_SAW "
        cmd.Connection = con

        dr = cmd.ExecuteReader
        While dr.Read
            Combobox2.Items.Add(dr.GetString(0))
        End While

        dr.Close()
        con.Close() 
vb.net ms-access-2010

评论

1赞 Dai 11/8/2023
您的代码似乎被截断了...
2赞 jmcilhinney 11/8/2023
如果第一个包含表名,为什么不能直接获取并将其插入 SQL 代码中呢?其他一切都完全相同,因此不需要重复。ComboBoxText
1赞 jmcilhinney 11/8/2023
如果只需要一列,则不要这样做。始终指定要检索的确切列,不要指定任何不打算使用的列。SELECT *
1赞 jmcilhinney 11/8/2023
不要像这样一个接一个地添加项目。使用 并绑定数据读取器。请参阅此处了解如何操作。ComboBoxBindingSource
0赞 June7 11/10/2023
为什么每个工具都有自己的表格?正如@jmcilhinney所说,引用第一个 tablename 组合框并将其插入 SQL: .消除 If Then Else 和对组合框所选行索引的引用。Select * from " & ComboBox1

答: 暂无答案