In this article I will explain with an example, how to select data from
MySQL database in Windows Forms (WinForms) Application using C# and VB.Net.
Database
I have made use of the following table Customers with the schema as follows.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
Form Design
The Form consists of following control:
DataGridView – For displaying data.
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Configuration;
using MySql.Data.MySqlClient;
VB.Net
Imports System.Data
Imports System.Configuration
Imports MySql.Data.MySqlClient
Selecting from MySQL Database in C# and VB.Net
Inside the Form_Load event handler, first the connection is read from Web.Config file.
Then, a connection to the database is established using the
MySqlConnection class and the records are fetched from the
Customers Table of
MySQL database.
Finally, the DataGridView is populated.
C#
private void Form1_Load(object sender, EventArgs e)
{
string sql = "SELECT CustomerId, Name, Country FROM Customers";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
using (MySqlDataAdapter sdr = new MySqlDataAdapter(sql, con))
{
using (DataTable dt = new DataTable())
{
sdr.Fill(dt);
dgvCustomers.DataSource = dt;
}
}
}
}
VB.Net
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim sql As String = "SELECT CustomerId, Name, Country FROM Customers"
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As MySqlConnection = New MySqlConnection(constr)
Using sdr As MySqlDataAdapter = New MySqlDataAdapter(sql, con)
Using dt As DataTable = New DataTable()
sdr.Fill(dt)
dgvCustomers.DataSource = dt
End Using
End Using
End Using
End Sub
Screenshot
Downloads