ASP.NET - GridView empty after page reload

428 Views Asked by At

I'm using a MySQL database to store some data, I've got a page in my ASP-project which should show the whole table, when you open up the page as a standard result.

Well actually it does, but just one time, if you reload the page or direct to another and back, the GridView doesn't show up. Connection to the db still exists... Here's my Code:

private Class.DB db;
protected void Page_Load(object sender, EventArgs e)
{
    this.db = (Class.DB)Session["DBConnection"];
    MySqlDataReader mdr = db.executeQuery(@"SELECT * FROM testtable;");
    GridDataView1.DataSource = mdr;
    GridDataView1.DataBind();
}

the GridView:

<asp:GridView ID="GridDataView1" runat="server" EmptyDataText="No Data!">
</asp:GridView>

My Query-method from my DB-class:

public MySqlDataReader executeQuery(String command)
{
    try
    {
        MySqlCommand cmd = new MySqlCommand(command, this.conn);
        MySqlDataReader mdr = cmd.ExecuteReader();
        return mdr;

    }
    catch
    {
        return null;
    }
}
2

There are 2 best solutions below

0
drdwilcox On BEST ANSWER

While your answer works, there is a better idiom that you could use. Since MySqlDataReader inherits from IDisposable, you could write:

protected void Page_Load(object sender, EventArgs e)
{
    this.db = (Class.DB)Session["DBConnection"];
    using (MySqlDataReader mdr = db.executeQuery(@"SELECT * FROM testtable;")) 
    {
        GridDataView1.DataSource = mdr;
        GridDataView1.DataBind();
    }
 }
0
EmbraceMyDuck On

Fixed it by debugging, forgot to close the DataReader after the first binding. Code should be:

protected void Page_Load(object sender, EventArgs e)
{
    this.db = (Class.DB)Session["DBConnection"];
    MySqlDataReader mdr = db.executeQuery(@"SELECT * FROM testtable;");
    GridDataView1.DataSource = mdr;
    GridDataView1.DataBind();
    mdr.Close();
 }

Hope i can help someone with that.