ITSourceCode.com

We Exist to Provide 100% Free Source Code and Tutorials

Custom Search

How to Fill Data in the ComboBox in VB.net

In this tutorial, I will teach you how to fill the data in the Combobox in VB.Net. With this, the record in the database will be displayed in the list control of the ComboBox. This is very helpful, because you can control whatever the records that you want to display in the ComboBox.

 
Let’s begin:

 

Now, create a database named<strong> “dbstudent”</strong> in MySql Database.

Then create a table in it.

[<mysql] CREATE TABLE IF NOT EXISTS `tblstudent` (
`ID` int( 11 ) NOT NULL AUTO_INCREMENT ,
`stud_id` varchar( 99 ) NOT NULL ,
`fname` varchar( 99 ) NOT NULL ,
PRIMARY KEY ( `ID` ) ,
UNIQUE KEY `stud_id` ( `stud_id` )
[/mysql] Open the Visual Studio 2008 and create a new Window Form Application. Drag a ComboBox on the Form and It will look like this.
fillcomboform
After setting up the Form, double click the Form and set the connection and declare all the classes that are needed above the Form1_Load.

  1. 'CREATE A PUBLIC FUNCTION FOR A CONNECTION
  2. Public Function MySQLconnection() As MySqlConnection
  3. 'RETURNING THE NEW CONNECTION
  4. Return New MySqlConnection("server=localhost;user id=root;database=dbstudent")
  5. End Function
  6. 'INITIALIZE A PUBLIC VARIABLE TO THE FUNCTION THAT YOU HAVE CREATED.
  7. Public con As MySqlConnection = MySQLconnection()
  8. 'SET AS THE BRIGDE BETWEEN THE DATABASE AND DATATABLE IN UPDATING AND SAVING THE DATA.
  9. Public da As New MySqlDataAdapter
  10. 'IT REPRESENT AN IN-MEMORY CACHE OF DATA IN THE DATABASE
  11. Public ds As New DataSet

After that, you have to set up data to be filled in the ComboBox and put it in the Form1_Load.

  1. Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  2. 'INTIALIZE THE NEW DATASET
  3. ds = New DataSet
  4. 'FOR RETRIEVING AND FILLING DATA IN THE TABLE
  5. da = New MySqlDataAdapter("SELECT * FROM tblstudent", con)
  6. da.Fill(ds)
  7.  
  8. With ComboBox1
  9. 'INTIALIZE THE DATASOURCE OF THE COMBOBOX
  10. .DataSource = ds.Tables(0)
  11. 'SET THE FIELD OF THE TABLE THAT WILL DISPLAY IN THE LIST CONTROL OF THE COMBOBOX.
  12. .DisplayMember = "fname"
  13. End With
  14. End Sub

Remider : Set your reference above the Public Class for the imports.

  1. 'SET YOUR REFFERENCES
  2. Imports MySql.Data.MySqlClient

Press F5 on the keyboard to run your project.

Facebook Comments

Check Your Domain Ranking

Leave a Reply

Your email address will not be published. Required fields are marked *

ITSourceCode.com © 2016 Frontier Theme

Subscribe For Latest Updates

Signup for our newsletter and get notified when we publish new articles for free!