Home > ASP.NET > How to fetch data from database in Asp.net



How to fetch data from database in Asp.net

In this article, we have described how to use Gridview in asp.net with C# with example code.


In this article, we have described how to use Gridview in asp.net with C# 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:

We must use the following namespaces to connect with Mysql database.

 

using System.Data;

using MySql.Data.MySqlClient;

using System.Configuration;

 

Aspx code 

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

 

<html xmlns="">

<head runat="server">

   <title>How to fetch data from database in Mysql</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#

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:*