Home > ASP.NET > How to populate Gridview with MySQL database



How to populate Gridview with MySQL database

In this article, we will explain how to populate Gridview with MySQL database with example code.


In this article, we will explain how to populate Gridview with MySQL database with example code .

Gridview is a control in asp.net .

Gridview is a very popular and useful control in C#. We can specify custom columns and styles .

Gridview automatically binds to and displays data from a data source control .

 

Required Namespaces:

you will need to use the following namespaces.

using System.Data;

using MySql.Data.MySqlClient;

using System.Configuration;

 

aspx page

We have used the gridview code below. You can have a look at it and learn.

<html xmlns="">

<head runat="server">

   <title>how to use gridview in ASP.NET</title>

</head>

<body>

   <form id="form1" runat="server">

       <asp:GridView ID="gvUsers" calss="table table-bordered responsive-table" AutoGenerateColumns="true" runat="server">

       </asp:GridView>

   </form>

</body>

</html>

 

C# code

We have explained below C# code with examples of some user information in this article .You can have a look at it and learn.

string mysqlcomnnection = Convert.ToString(ConfigurationManager.AppSettings["connection"]);

protected void Page_Load(object sender, EventArgs e)

{

    if (!IsPostBack)

    {

 

        BindGridview();

    }

}

private void BindGridview()

{

    MySqlConnection con = new MySqlConnection(mysqlcomnnection);

    string CommandText = "Select userid as UserID, firstname as FirstName,lastname as LastName from users";

    MySqlCommand cmd = new MySqlCommand(CommandText, con);

    MySqlDataAdapter sda = new MySqlDataAdapter(cmd);

    DataTable dt = new DataTable();

    sda.Fill(dt);

    gvUsers.DataSource = dt;

    gvUsers.DataBind();

}

 




Note: All contents are copyright of their authors.



Comments



Leave a Reply

Comment:*
Email ID:*


Name:*