Access Primary Key usage/role

巧了我就是萌 提交于 2019-12-02 07:50:07

Your CBO shows AdminID because that is what you fill it with. If you bind the table to the CBO, you can use DisplayMember to show one thing, and ValueMember to return another to your code:

Private ACEConnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= InfoSystem.accdb"
Private dtAdmin As DataTable
...
Private Sub SetupCBO
    Dim SQL = "SELECT AdminId, AdminName FROM tblAdmin"

    Using dbcon As New OleDbConnection(ACEConnStr)
        Using cmd As New OleDbCommand(SQL, dbcon)

            dbcon.Open()
            dtAdmin = New DataTable

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

    cboAdmin.DataSource = dtAdmin
    cboAdmin.DisplayMember = "AdminName"     ' what to show
    cboAdmin.ValueMember = "AdminId"         ' what field to report
End Sub

The first thing to note is that there is no code to populate the CBO directly. Using a DataSource, the cbo will get the data from the underlying table. The DisplayMember tells it which column to...well, display, and the ValueMember allows your code to be able to fetch that PrimaryKey/Id to positively know which "Steve" or "Bob" is logging in.

Also note that you don't absolutely need a DataAdapter just to fill one table. Nor do you need DataSet. As shown, you can use the Load method with a DataReader to directly fill a table. The Using blocks close and dispose of those objects freeing resources.

When bound, you would generally use the SelectedValueChanged event and use the .SelectedValue.

In this case, the SelectedItem will be a DataRowView object because NET creates a DataView wrapper. If the data source was a List(Of Employee) or a List(of Widget), the SelectedItem will be the selected Employee or Widget.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!