1

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

Laziale
  • 7,965
  • 46
  • 146
  • 262
  • For starters, you can probably change `catch` to `catch(Exception ex)` so you can see if you are actually getting an exception. An empty `catch` block will hide your exception. – Bryan Crosby Nov 21 '11 at 17:25

3 Answers3

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.

Brian
  • 5,069
  • 7
  • 37
  • 47
Adi
  • 61
  • 6
  • that was not the problem. The problem was that you cannot use a DataReader to populate a GridView if paging is enabled. – slfan Nov 22 '11 at 12:51
  • Yes you are right...it just skipped my mind. With DATAREADER as DATASOURCE, SERVER SIDE PAGING IS NOT ALLOWED. One will have to use DATAADAPTER-DATASET – Adi Nov 23 '11 at 10:44
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);
 ...
slfan
  • 8,950
  • 115
  • 65
  • 78
0

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

drdwilcox
  • 3,833
  • 17
  • 19