简体   繁体   English

ASP.NET-页面重新加载后GridView为空

[英]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. 我正在使用MySQL数据库存储一些数据,我的ASP项目中有一个页面,当您打开页面作为标准结果时,该页面应显示整个表。

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. 确实可以,但是只有一次,如果重新加载页面或直接指向另一个页面并返回,则GridView不会显示。 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: 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;
    }
}

Fixed it by debugging, forgot to close the DataReader after the first binding. 通过调试修复了该问题,在第一次绑定后忘记关闭DataReader。 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. 希望我可以帮助某人。

While your answer works, there is a better idiom that you could use. 当您的答案有效时,您可以使用更好的习惯用法。 Since MySqlDataReader inherits from IDisposable , you could write: 由于MySqlDataReader继承自IDisposable ,因此您可以编写:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM