如何使用 Access 数据库中的记录填充组合框

How to fill a ComboBox using records from an Access database

我想检索数据并在 ComboBox 中显示,但它显示为空白。

这是我的代码:

Imports System.Data.OleDb

Public Class frmAirwaybill

    Private Sub frmAirwaybill_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Dim cm As OleDbCommand = New OleDbCommand("select acc_no from tblshipper order by acc_no")
        cm.Connection = DBconnection()
        Dim dr As OleDbDataReader = cm.ExecuteReader
        Do While (dr.Read())
            txtAccountNo.Items.Add(dr.Item("acc_no"))
        Loop
        dr.Close()
        DBconnection.Close()
    End Sub
End Class*

txtAccountNo 是 ComboBox

当加载表单时,我想要的是从我的数据库加载accno。我该怎么做?

这是显示 ComboBox 为空值的屏幕截图:

我的数据库连接正常。

这是我在模块文件上的连接

Public Function DBconnection() As OleDbConnection

        Dim con As New OleDb.OleDbConnection
        Dim constring As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Application.StartupPath & "\SmartshipG2.mdb"
        con = New OleDb.OleDbConnection(constring)
        con.Open()
        Return con

End Function

首先要注意的是你还没有打开连接。这可能是根本原因。

也就是说,您最好使用 DataTable 绑定到 ComboBox.DataSource 并设置 .DisplayMember.ValueMember 属性。

我也会考虑实施 Using:

Sometimes your code requires an unmanaged resource, such as a file handle, a COM wrapper, or a SQL connection. A Using block guarantees the disposal of one or more such resources when your code is finished with them. This makes them available for other code to use.

最后,考虑给您的 ComboBox 一个更好的前缀。 txt 通常用于 TextBox 控件。我使用 cmb 而其他人可能使用 cbx。所以在这种情况下 cmbAccountNo 似乎更合适。

经过更改,您的代码将如下所示:

Dim dt As New DataTable
Using con As OleDbConnection New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Application.StartupPath & "\SmartshipG2.mdb"),
      cmd As New OleDbCommand("SELECT [acc_no] FROM [tblshipper] ORDER BY [acc_no]", con)
    con.Open()

    dt.Load(cmd.ExecuteReader())
End Using

cmbAccountNo.DataSource = dt
cmbAccountNo.DisplayMember = "acc_no"
cmbAccountNo.ValueMember = "acc_no"