如何分页gridView

时间:2013-04-09 19:40:11

标签: asp.net

我有网格视图:

 <asp:GridView ID="GridViewCosts" runat="server"   CellPadding="4" ForeColor="#333333" GridLines="None" ShowFooter="True" ShowHeaderWhenEmpty="True" AutoGenerateColumns="False" OnRowDeleting="GridViewCosts_RowDeleting" Width="387px" OnSelectedIndexChanged="GridViewCosts_SelectedIndexChanged" AllowPaging="true" AllowSorting="true" 
PageSize="5" >

但是这给了我错误:The data source does not support server-side data paging.

在代码背后的

我有这样的事情:

GridViewCosts.DataSource = rdr;
Line 55:                    GridViewCosts.DataBind();

如何分页我没有dataSource的gridView

更新 我修改我有这个

 <asp:GridView ID="GridViewCosts" runat="server"   CellPadding="4" 
        ForeColor="#333333" GridLines="None" ShowFooter="True" ShowHeaderWhenEmpty="True"
         AutoGenerateColumns="False" OnRowDeleting="GridViewCosts_RowDeleting" Width="387px"
         OnSelectedIndexChanged="GridViewCosts_SelectedIndexChanged" 
         OnPageIndexChanging="GridViewCosts_PageIndexChanging"

        PageSize="5" >
代码中的

后面有这个:

  public void getViewProfit()
        {
            string connectionString = cs.getConnection();
            string query = "select Id ,name,value,Description,DateCreate from AllCostView where IdUser = '" + cui.getCurrentId() + "'";
            using (SqlConnection myConnection = new SqlConnection(connectionString))
            {
                myConnection.Open();
                SqlCommand command = new SqlCommand(query, myConnection);
                using (SqlDataReader rdr = command.ExecuteReader())
                {
                   GridViewCosts.DataSource = rdr;
                   GridViewCosts.DataBind();
                }

            }
        }

  protected void GridViewCosts_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridViewCosts.PageIndex = e.NewPageIndex;
            getViewProfit();
        }

不再有任何错误,但仍未显示分页

1 个答案:

答案 0 :(得分:1)

如果您使用了datareader?是的,请使用DataSet / DataTable代替Datareader。由于Datareader不支持分页和排序功能,因此DataReader从数据库中检索ReadOnly,ForwardOnly数据流。

你错过了gridview的pageindexChanging属性,

见下文

<asp:GridView ID="GridViewCosts" runat="server"   CellPadding="4" ForeColor="#333333" GridLines="None" ShowFooter="True" ShowHeaderWhenEmpty="True" AutoGenerateColumns="False" OnRowDeleting="GridViewCosts_RowDeleting" Width="387px" OnSelectedIndexChanged="GridViewCosts_SelectedIndexChanged" AllowPaging="true" AllowSorting="true" 
PageSize="5" **OnPageIndexChanging="GridViewCosts_PageIndexChanging"**>

代码背后:

protected void GridViewCosts1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    GridViewCosts.PageIndex = e.NewPageIndex;

    //rebind your gridview .    

}