How to Fill Up a VB Combo Box With Data From Database Table

Save

In Visual Basic, combo boxes are often used in data entry programs and when submitting information via online forms. For instance, you might need to select from a list of states or zip codes and clicking a drop-down list presents you with various selections. A combo box is populated with user-defined items which are typically added by the programmer at design time, but you can also fill up a combo box with items from a database table using just a few lines of code.

Things You'll Need

  • Visual Basic installed
  • Database file
  • Launch Visual Basic by clicking the “Start” button and selecting “Programs,” “Microsoft Visual Studio” and then “Microsoft Visual Basic [version number]."

  • Select "Standard EXE" under the "New Project" dialog box. Click "Open" to open a new form.

  • Click on the "ComboBox" control from the Toolbox on the left and drag it to the center form. Set its properties under the Properties window on the right.

  • Add an "ADO" control into the form. Set its "Visible" property to “False.”

  • Click the "View Code" button on top of the Project Explorer window to begin adding code. In the example below, the 50 U.S. states will be added into the combo box from a database table. When the form loads at runtime, the combo box is filled up automatically. Go to the "Form_Load" event and enter code similar to following:

    Dim conn As New ADODB.Connection
    Dim rs As New ADODB.Recordset
    Set conn = DBEngine.OpenDatabase(App.Path & "\dbDatabase.mdb")
    Set rs = conn.OpenRecordset("tblStates")

    If rs.RecordCount > 0 Then
    Do While Not rs.EOF
    With Combo1
    .AddItem rs.Fields("USStateName")
    End With
    .MoveNext
    Loop
    End If

  • Press the “F5” key on your keyboard to run your program.

  • Save your Visual Basic project by clicking "File” and then “Save Project As" from the menu.

References

  • Photo Credit Hemera Technologies/AbleStock.com/Getty Images
Promoted By Zergnet

Comments

You May Also Like

  • How to Use a ComboBox in Visual Basic

    The ComboBox in Visual Basic offers more options than two related controls, the ListBox and Textbox. These include sorting the elements in...

  • Visual Basic Combo Box Tutorial

    The Visual Basic ComboBox component is a common user interface element in Windows programs. It allows the user to select one item...

  • Visual Studio SQL Tutorial

    SQL Server is a system that allows developers to create and manage databases. It runs as a service and has no user...

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

M
Is DIY in your DNA? Become part of our maker community.
Submit Your Work!