In this article I will explain how to connect (Bind) GridView to MySql database in ASP.Net using C# and VB.Net.
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.
MySql Connection String
Below is the connection string to the MySql Database.
<add name="constr" connectionString="Data Source=localhost;port=3306;Initial Catalog=SampleDB;User Id=mudassar;password=pass@123"/>
You will need to import the following namespaces.
Binding the GridView with records from MySQL Database Table
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 Page Load event of the page, I am populating the GridView control with records from the MySql database using a DataTable.
protected void Page_Load(object sender, EventArgs e)
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
using (MySqlCommand cmd = new MySqlCommand("SELECT * FROM Customers"))
using (MySqlDataAdapter sda = new MySqlDataAdapter())
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
GridView1.DataSource = dt;
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New MySqlConnection(constr)
Using cmd As New MySqlCommand("SELECT * FROM Customers")
Using sda As New MySqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
Using dt As New DataTable()
GridView1.DataSource = dt