0

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;
    }
}
hensing1
  • 187
  • 13
EmbraceMyDuck
  • 183
  • 2
  • 10
  • 1
    First your catch returns NULL, so it you get an error you wont know it or what it is. You need to fix that to show/track error somehow. Also try stepping through your code in debug mode – Brad Feb 25 '19 at 14:57

2 Answers2

0

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.

EmbraceMyDuck
  • 183
  • 2
  • 10
0

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();
    }
 }
drdwilcox
  • 3,833
  • 17
  • 19