Access Primary Key usage/role

前端 未结 1 1863
有刺的猬
有刺的猬 2021-01-29 03:08

My question is in relation to connecting a VB.net project to an Access DB. Must I have a primary key in my table, or have is there a way to alter my code to not look for a PK?<

相关标签:
1条回答
  • 2021-01-29 03:28

    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.

    0 讨论(0)
提交回复
热议问题