In this article I will explain with an example, how to fill (populate) DataTable using MySqlDataAdapter in 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.
Download and Install the MySQL Connector
You will need to download and install the MySQLConnector in order to connect to the MySQL database in ASP.Net.
After installation is complete you need to open Windows Explorer and look for the MySql installation in the Program Files folder of your Windows drive.
There you will find a folder for MySQL Connector and inside that you will find the MySql.Data.dll which you need to copy inside the BIN folder of your project.
Form Design
The following Form consists of a DataGridView control.
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using MySql.Data.MySqlClient;
VB.Net
Imports System.Data
Imports MySql.Data.MySqlClient
Fill (Populate) DataTable using MySqlDataAdapter in C# and VB.Net
Inside the Form Load event handler, the BindGrid method is called.
nside BindGrid method, MySqlDataAdapter object is initialized with the MySqlCommand and using the Fill function, the DataTable is populated with the records from database.
Finally, the DataTable is used to populate the DataGridView.
C#
private void Form1_Load(object sender, EventArgs e)
{
this.BindGrid();
}
private void BindGrid()
{
string conString = @"Data Source=localhost;port=3306;Initial Catalog=AjaxSamples;User Id=mudassar;password=pass@123";
using (MySqlConnection con = new MySqlConnection(conString))
{
using (MySqlCommand cmd = new MySqlCommand("SELECT * FROM Customers", con))
{
cmd.CommandType = CommandType.Text;
using (MySqlDataAdapter sda = new MySqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
}
}
VB.Net
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Me.BindGrid()
End Sub
Private Sub BindGrid()
Dim conString As String = "Data Source=localhost;port=3306;Initial Catalog=AjaxSamples;User Id=mudassar;password=pass@123"
Using con As New MySqlConnection(conString)
Using cmd As New MySqlCommand("SELECT * FROM Customers", con)
cmd.CommandType = CommandType.Text
Using sda As New MySqlDataAdapter(cmd)
Using dt As New DataTable()
sda.Fill(dt)
dataGridView1.DataSource = dt
End Using
End Using
End Using
End Using
End Sub
Screenshot
Downloads