How to Populate Listbox in Visual Basic with MySQL Database

1
961

Today, I will teach you how to  Populate Listbox in Visual Basic with MySQL Database. This will show you how the data of a table in the database are displayed in a ListBox.

Let’s begin:
First create a Database named “info”.

  1. CREATE DATABASE `dbinformations` ;

Then, create a table named “persons”.

  1. CREATE TABLE `dbinformations`.`person` (
  2. `FirstName` TEXT NOT NULL ,
  3. `LastName` TEXT NOT NULL ,
  4. PRIMARY KEY ( `ID` )

After creating a table in the database, create a query for inserting data in the MySQL Database.

  1. INSERT INTO `person` ( `FirstName` , `LastName` )
  2. VALUES ('Janno', 'Palcios'),
  3. ('Mark', 'Palcios'),
  4. ('Craig', 'Palcios')

After inserting data in the database, open the Visual Basic and create a new Windows Form Application. In the Form add a ListBox.
filldatalistboxform
After dragging ListBox, double click the Form and set up the connection to MySQL Database and Visual Basic. After that, declare all the classes that are needed above the.Form1_Load

  1. Public con As MySqlConnection = New MySqlConnection("server=localhost;user id=root;database=dbinformations")
  2. Public cmd As New MySqlCommand
  3. Public da As New MySqlDataAdapter
  4. Public ds As New DataSet

In the Form1_Load, you have to fill the data in the ListBox that came from the database in the first load Form.

  1. Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  2. 'OPENING THE CONNECTION
  3. con.Open()
  4. 'SET YOUR COMMANDS TO PROVIDE A TEXT-BASE INTERFACE INTO THE MYSQL DATABASE SERVER.
  5. 'AND ONCE IT'S CONNECTED, YOU CAN MAKE QUERY OR MANY OTHER OPERATION.
  6. With cmd
  7. .Connection = con
  8. .CommandText = "SELECT * FROM person"
  9. End With
  10. 'SET THIS STORED PROCEDURE TO SELECT THE RECORD IN THE DATASOURCE
  11. da.SelectCommand = cmd
  12. 'REFRESHES THE ROWS IN THE DATASER TO MATCH IN THE DATASOURCE USING THE TABLE NAME
  13. da.Fill(ds, "person")
  14. With ListBox1
  15. 'SET THE DATA SOURCE FOR THE LISTBOX
  16. .DataSource = ds.Tables(0)
  17. 'SET A PROPERTY TO DISPLAY THE DATA THAT CAME FROM THE DATABASE IN THE LISTBOX
  18. .DisplayMember = "FirstName"
  19. End With
  20. 'CLOSING THE CONNECTION
  21. con.Close()
  22. End Sub

If you have any questions or suggestions on how to populate listbox, just contact through our contact page.

Download the complete source code Here

Facebook Comments
(Visited 767 times, 1 visits today)

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here