VB.NET MySQL: Displaying Data on DataGridView

This is a serial tutorial of VB.NET and MySQL, So make sure you understand the previous article first.

Read also: Connecting VB.NET to MySQL Database using MySQL Connector

Next, we'll try to bind data from a database table to DataGridView.
I have an example table named kategori.
Query:
Table values:

For UI design, add DataGridView into a form then name it grdData.

Type code as below:
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

            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 on datagridview.

Post a Comment

0 Comments