gridview control and paging asp.net

百般思念 提交于 2019-12-11 05:19:40

问题


I have a gridview which gets populated in the backend code. I am trying to implement paging now, but when I am trying my way, I am getting nothing. Here is my piece of code:

public void generateTable()
{
    conn.ConnectionString = connString;
    SqlCommand comm = new SqlCommand("ViewBusinessInfo", conn);
    comm.CommandType = CommandType.StoredProcedure;
    comm.CommandTimeout = 2;
    try
    {
        conn.Open();
        SqlDataReader rdr = comm.ExecuteReader();

        if (rdr.HasRows)
        {
            gvAssociation.DataSource = rdr;
            gvAssociation.DataBind();
            gvAssociation.AllowPaging = true;
            gvAssociation.PageSize = 10;
            rdr.Close();
        }
        else
        {
            lblResult.Text = "No businesses found.";
            lblResult.Visible = true;
        }

    }
    catch
    {
    }
    finally
    {
        conn.Close();
    }
}

Can anyone advice what am I doing wrong and I can't get the paging in the gridview? Thx in advance, Laziale


回答1:


You cannot use paging with a DataReader. You should fill your data into a Dataset or a Datatable using a DataAdapter. Something like this:

 SqlCommand myCommand = new SqlCommand("ViewBusinessInfo", conn);
 SqlDataAdapter myAdapter = new SqlDataAdapter(myCommand))
 DataTable dt = new DataTable();
 myAdapter.Fill(dt);
 ...



回答2:


The allowPaging and pagesize property of the gridview can be added in the .aspx, where the gridview tag is present.

<asp:GridView ID="gridView" OnPageIndexChanging="gridView_PageIndexChanging"  AllowPaging="True" pagesize="10" runat="server" />

Additionally, to make the paging links work, you have to add the following code in the gridview_PageIndexChanging event of the gridview:

protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
   gridView.PageIndex = e.NewPageIndex;
   gridView.DataBind();
}

Hope this is helpful.




回答3:


Set the AllowPaging and PageSize declaratively, or do so before you call DataBind().



来源:https://stackoverflow.com/questions/8215826/gridview-control-and-paging-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!