How to fetching data in asp.net using MySql database


Hi All,

This is the just continues post of my previous post. In this post we will see how to fetch the data from mysql database and display in asp.net gridview.

Step 1: Create the demo asp.net project.

Step 2: Install the Mysql.Data.MySqlClient.Net dll from NuGet Package Manager Tool.

Step 3: Create the tblEmp in Mysql database like this

Step 4: Take the gridview in aspx page like this

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="MySql.aspx.cs" Inherits="Default2" %>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" Runat="Server">
    <br />
<div class="container">

    <div class="panel panel-primary">
      <div class="panel-heading"><b>Fetching data using Mysql data Adapter</b></div>
      <div class="panel-body">
          <div class="table-responsive">
         <asp:GridView ID="GridView1" runat="server" CssClass="table table-striped">
          </asp:GridView> 
          </div>
     
</div>
    </div>
    </div>
</asp:Content>



Step 5: Write the code in code behind file like this


using System;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;
using System.Data;

public partial class Default2 : System.Web.UI.Page
{
    MySqlConnection con = new MySqlConnection("data source=localhost;port=3306;database=test;user id=root;SslMode=none;password=admin");
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            
            fillGrid();
            //This below code is written to implement the bootstrap on Gridview
            GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
        }
    }

    private void fillGrid()
    {
        using (MySqlCommand cmd=new MySqlCommand("Select * from tblEmp",con))
        {
            MySqlDataAdapter da = new MySqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }
}

In the above code we show that we have implemented MySql.Data.MySqlClient namespace and we are using the MySqlCommand and MySqlDataAdapter from above namespace and remaining code is same as how we write with sql server database.

Step 6: Run the application we will see the output like this

Advertisement