asp.net上的GridView AllowPaging

时间:2011-04-26 16:49:47

标签: c# .net asp.net sql gridview

我有一个gridview,我启用了分页并添加了事件处理程序。一切都工作正常,但我必须按两次每个数字才能更新。

下面是我用于初始加载的代码和用于页面添加事件处理程序的调用

protected void Page_Load(object sender, EventArgs e)
        {

            query = "SELECT log_id, use_username AS `Username`, log_type AS `Type`, "
                + "log_description AS `Description`, DATE_FORMAT(log_date, '%d-%m-%Y') AS `Date Created`, "
                + "DATE_FORMAT(log_time, '%H:%i') AS `Time Created` FROM log l, users u "
                + "WHERE l.log_userID = u.use_id";
            new DatabaseWork().loadGrid(query, tblLog);
            if (tblLog.Rows.Count == 0)
            {
                lblNoData.Visible = true;
            }

        }

protected void tblLog_PageChanging(object sender, GridViewPageEventArgs e)
        {
            new DatabaseWork().loadGrid(query, tblLog);
            tblLog.PageIndex = e.NewPageIndex;
        }

下面是用于将数据绑定到datagird的代码,该数据从上面的方法中调用

public void loadGrid(string query, GridView tblGrid)
        {
            using (DatabaseWork db = new DatabaseWork())
            {
                using (MySqlCommand cmd = new MySqlCommand(query, db.conn))
                {
                    using (MySqlDataAdapter da = new MySqlDataAdapter(cmd))
                    {

                        DataSet ds = new DataSet();
                        da.Fill(ds);
                        tblGrid.DataSource = ds.Tables[0];
                        tblGrid.DataBind();
                    }

                }
            }

一切正常,但每个页码必须按两次,我不明白为什么。

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

您需要在查询If(!Page.IspostBack)

之前设置此页面回发条件
protected void Page_Load(object sender, EventArgs e)
    {
      If(!Page.IspostBack)
      {
        query = "SELECT log_id, use_username AS `Username`, log_type AS `Type`, "
            + "log_description AS `Description`, DATE_FORMAT(log_date, '%d-%m-%Y') AS `Date Created`, "
            + "DATE_FORMAT(log_time, '%H:%i') AS `Time Created` FROM log l, users u "
            + "WHERE l.log_userID = u.use_id";
        new DatabaseWork().loadGrid(query, tblLog);
        if (tblLog.Rows.Count == 0)
        {
            lblNoData.Visible = true;
        }
      }
    }

修改

protected void tblLog_PageChanging(object sender, GridViewPageEventArgs e)
    {
       query = "SELECT log_id, use_username AS `Username`, log_type AS `Type`, "
        + "log_description AS `Description`, DATE_FORMAT(log_date, '%d-%m-%Y') AS `Date Created`, "
        + "DATE_FORMAT(log_time, '%H:%i') AS `Time Created` FROM log l, users u "
        + "WHERE l.log_userID = u.use_id";

        new DatabaseWork().loadGrid(query, tblLog);
        tblLog.PageIndex = e.NewPageIndex;
    }

答案 1 :(得分:1)

我想问题是Page_Load正在GridView_PageChanging之前执行。

如果首次使用IsPostBack属性加载页面,请尝试加载数据。