Search code examples
c#mysqlasp.netvisual-studiomysqldatareader

ASP.NET - GridView empty after page reload


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;
    }
}

Solution

  • 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();
        }
     }