VB.NET MySQL: ComboBox Data Binding

On previous articles we discussed:
Now, I'll show you an example of how to bind MySQL data to a ComboBox List.
We're still using the previous project solution and database. Add a ComboBox control, name it cboKategori.

Code that need to be added as following:
cboKategori.DataSource = myData
cboKategori.DisplayMember = "namakategori"
cboKategori.ValueMember = "kodekategori"


And below is the complete code:
Imports MySql.Data.MySqlClient
Imports System.Data
Public Class Form1
    Dim conn As MySqlConnection
    Dim myCommand As New MySqlCommand
    Dim myAdapter As New MySqlDataAdapter
    Dim myData As New DataTable
    Dim SQL As String

    Private Sub Form1_Load(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles MyBase.Load
        conn = New MySqlConnection()
        conn.ConnectionString = "server=localhost;user id=root;" & _
                                "password=;database=latihan"
        Try
            conn.Open()
            SQL = "Select kodekategori, namakategori From kategori"

            myCommand.Connection = conn
            myCommand.CommandText = SQL

            myAdapter.SelectCommand = myCommand
            myAdapter.Fill(myData)

            grdData.DataSource = myData


            cboKategori.DataSource = myData
            cboKategori.DisplayMember = "namakategori" 
            cboKategori.ValueMember = "kodekategori"

            conn.Close()
        Catch myerror As MySqlException
            MessageBox.Show("Error: " & myerror.Message)
        Finally
            conn.Dispose()
        End Try
    End Sub
End Class


Try to run/debug application. Data will be displayed in combobox list.



This tutorial also available @ youtube:




Post a Comment

0 Comments