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 Controls
The below 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
If you are aware of ADO.Net then using MySql will be lot simpler as the MySql Connector classes have very similar names to that of the ADO.Net classes. For example in ADO.Net we have SqlConnection class and the corresponding class in MySql is MySqlConnection.
Inside the Form Load event of the page, the DataGridView control is populated with records from the MySql database using a DataTable.
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