简体   繁体   中英

VB.Net 2010 - Populating a ComboBox from an MDB access database

I am currently trying to populate a drop box on a form in VB.Net from an MDB database for a project I am working on for work.

I have a table called "Months" in a database called "cancmov", and the field i am trying to pull from is called MoveMonth.

The current code i am using is:-

Private Sub drpMovedFrom_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles drpMovedFrom.SelectedIndexChanged


    Dim ConnnectionString As String = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Admin\Desktop\CancellationsAndMovements\CancellationsandMovements\cancmov.mdb"
    Dim db As String = "SELECT MoveMonth FROM Months"
    Dim cn As New OleDbConnection(ConnnectionString)
    Dim da As New OleDbDataAdapter(db, cn)
    Dim ds As New DataSet()

    da.Fill(ds, "MoveMonth")

    With drpMovedFrom
        .DataSource = ds.Tables("MoveMonth")
        .SelectedIndex = 0
    End With

End Sub

As you can probably gather from the above, I am currently in the process of learning, so a lot of the above i am trying to get my head around. I actually pulled the above code from a similar question that had been asked i found on google. Any help will be greatly appreciated, even if it is just to point me at a resource where i can learn to do this for myself.

Thanking you in advance.

A couple things right off the bat:

You are calling this code when the drop down index changes. Probably not what you want since it will always set it back to zero.

Also, try enclosing your disposable objects in using brackets:

Private ds As New DataSet()
Private ConnnectionString As String = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Admin\Desktop\CancellationsAndMovements\CancellationsandMovements\cancmov.mdb"

Protected Overrides Sub OnLoad(e As EventArgs)
  Dim db As String = "SELECT MoveMonth FROM Months"

  Using cn As New OleDbConnection(ConnnectionString)
    Using da As New OleDbDataAdapter(db, cn)
      da.Fill(ds, "MoveMonth")
    End Using
  End Using

  With drpMovedFrom
      .DisplayMember = "MoveMonth"
      .DataSource = ds.Tables("MoveMonth")
      .SelectedIndex = 0
  End With

  MyBase.OnLoad(e)
End Sub

Also, the ComboBox has DisplayMember and ValueMember properties that you map to your DataSource. DisplayMember is the value you see visible in the list, ValueMember is typically an ID value for the visible property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM