I attempted to get the records from the MySQL database and display it on a Grid View but nothing appeared. The code is below:

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

public partial class _Default : System.Web.UI.Page 
{
    
    protected void Page_Load(object sender, EventArgs e)
    {
        string MyConString = "SERVER=localhost;" +
        "DATABASE=mysql;" +
        "UID=root;" +
        "PASSWORD=bamboboy;";
        MySqlConnection connection = new MySqlConnection(MyConString);
        MySqlCommand command = connection.CreateCommand();
        command.CommandText = "select * from corporate";
        connection.Open();
        MySqlDataAdapter myadapter = new MySqlDataAdapter(command);
        DataSet dts = new DataSet();
        myadapter.Fill(dts);
        GridView1.DataSource = dts.Tables[0];
        connection.Close();
    }

    protected void GridView1_SelectedIndexChanged1(object sender, EventArgs e)
    {

    }
}

Recommended Answers

All 4 Replies

You need to call dataBind() on the GridView to actually make it display the data. All you have done is tell what its data source is. Also, you don't need to specifically open and close a connection for a dataAdapter, it takes care of that itself so you're using two connections here when you don't have to.

Hope that helps,

Have you checked to make sure the dataTable actually has data in it?

Yes it works. Upon binding the data to the grid, I can now see the data.

For binding Gridview for asp.net use below code
GridView1.DataSource = dts.Tables[0];
GridView1.DataBind();

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.