从数据库记录取决于分页

时间:2013-06-28 05:04:02

标签: c# asp.net database paging

protected void GridviewArchived_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    GridviewArchived.PageIndex = e.NewPageIndex;
    DisplayArchivedNews();
}

private void DisplayArchivedNews()
{
    using (SqlConnection Con = new SqlConnection(connection1))
    {
        SqlCommand Cmd = new SqlCommand("udspGetArchivedNews", Con);
        Cmd.CommandType = CommandType.StoredProcedure;
        Con.Open();
        Cmd.ExecuteNonQuery();
        Con.Close();
        DataSet ds = new DataSet();
        SqlDataAdapter da = new SqlDataAdapter(Cmd);
        da.Fill(ds);
        DataTable dt = ds.Tables[0];
        int totalrecord = ds.Tables[0].Rows.Count;
        GridviewArchived.DataSource = ds;
        GridviewArchived.DataBind();
        if (totalrecord > 0)
        {
            for (int i = 0; i < totalrecord; i++)
            {
                if( File.Exists(Server.MapPath("~//NewsFolder//Page1//" + GridviewArchived.DataKeys[i].Values["News_ID"].ToString().ToString() + (".PDF"))))
                {
                    HyperLink link = new HyperLink();
                    link.Text = "Page1";
                    link.Target = "blank";
                    link.NavigateUrl = "~//NewsFolder//Page1//" + GridviewArchived.DataKeys[i].Values["News_ID"].ToString() + (".pdf");
                    GridviewArchived.Rows[i].Cells[2].Controls.Add(link);

                }

                }

                }


            }
        }

Pagesize为10,但是当总记录数大于pagesize时,它会引发以下异常:

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index.

什么是解决方案,以便记录自动转到下一页索引?

1 个答案:

答案 0 :(得分:0)

为了在分页中显示gridview的记录,有两个选项

您可以使用gridview添加对象数据源并通过它显示分页,另一个选项是使用jquery Datatable进行分页。