Step By Step Bind MySQL Data To ASP.NET GridView

Firstly, let's create a table in MySQL database, I have XAMPP up and running on my PC.

 

Here in MySQL database I have created 'Emp' table and added 3-4 records,
 
 
 
Now, create a new ASP.NET Web Application Project, shown as per the following screen and give a name 'WebMySqlData'.
 
 
 
Select Empty Template and click 'Ok' . 
 
 
 
Add new Web Form and give a name 'WebForm1.aspx' .
 
 
 
Now Open toolbox, go to Data section and drag and drop 'GridView' control on web page.
 
 
Next step to add MySql Dll, for that go to tools, then NuGet Package Manager and click Manage Nuget Package for Solution.

 
 
Search for mysql, and select MySql.Data from list, cick on 'Install' and complete the process.
 
 
 
Add the following reference in your project. 
  1. using MySql.Data.MySqlClient;  
  2. using System.Configuration;  
  3. using System.Data;  
 
 
Next, you have to add connection string, open your web.config file and add the following code, don't forget to change credentials. 
  1.  <connectionStrings>  
  2.     <add name="default" connectionString="Data Source=localhost;port=3306;Initial Catalog=test;User Id=root;password="/>  
  3. </connectionStrings>  
Now, open your WebForm1.aspx.cs file and add the following code in Page Load Section. Here we are going to connect MySql Database and then bind the data in GridView using MySqlCommand and MySqlDataAdapter. 
  1. protected void Page_Load(object sender, EventArgs e)  
  2.       {  
  3.           if (!this.IsPostBack)  
  4.           {  
  5.               string constr = ConfigurationManager.ConnectionStrings["default"].ConnectionString;  
  6.               using (MySqlConnection con = new MySqlConnection(constr))  
  7.               {  
  8.                   using (MySqlCommand cmd = new MySqlCommand("SELECT EmpId,EmpName FROM Emp"))  
  9.                   {  
  10.                       using (MySqlDataAdapter da = new MySqlDataAdapter())  
  11.                       {  
  12.                           cmd.Connection = con;  
  13.                           da.SelectCommand = cmd;  
  14.                           using (DataTable dt = new DataTable())  
  15.                           {  
  16.                               da.Fill(dt);  
  17.                               GridView1.DataSource = dt;  
  18.                               GridView1.DataBind();  
  19.                           }  
  20.                       }  
  21.                   }  
  22.               }  
  23.           }  
  24.       }  
Save and run your application and check your Grid, it will display data from Emp Table from MySQL database.
 
EMP 
Hope you liked the simple steps to bind MySQL data to ASP.NET GridView.

Up Next
    Ebook Download
    View all
    Learn
    View all