zkanoca
zkanoca

Reputation: 9918

asp.net gridview pagination not displayed until refreshing

I have a DataGridView on a page. When I call that page whole list comes. I have decided to add pagination to the GridView.

 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id" OnRowDeleting="GridView1_Del" OnSelectedIndexChanging="GridView1_Sel"  OnPageIndexChanging="GridView1_PageIndexChanging">
            <Columns>
                <asp:BoundField DataField="id" HeaderText="Id" SortExpression="id" Visible="false" />
                <asp:BoundField DataField="name" HeaderText="Name" SortExpression="name" />
                <asp:BoundField DataField="author" HeaderText="Author" SortExpression="author" />
                <asp:BoundField DataField="active" HeaderText="Active" SortExpression="active" />
                <asp:CommandField HeaderText="Delete" SelectText="Delete"  ShowDeleteButton="True" ButtonType="Button" />
            </Columns>
        </asp:GridView>



//Page_Load()
gridFill();
GridView1.AllowPaging = true;
GridView1.PageSize = 10;

gridFill() method fills the GridView.

public void gridFill()
{
    conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:/inetpub/example.com/db/db.mdb");
    sql = "SELECT  id, name, author, active, FROM [table]";
    dt = new DataTable();

    try
    {
        if (conn.State != ConnectionState.Open) conn.Open();
        comm= new OleDbCommand(sql, conn);
        da= new OleDbDataAdapter(comm);

        da.Fill(dt);

        if (dt.Rows.Count > 0)
        {
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }

    catch (System.Data.OleDb.OleDbException ex)
    {
        string msg = "Error: ";
        msg += ex.Message;
        throw new Exception(msg);
    }

    finally
    {
        conn.Close();
    }
}

When I call the page it still gets all the rows at once. Also if I click 11th or later (because I limit the paging to 10 rows) rows for deleting I get index error.

So I have added another Button labeled as 'Refresh' which calls gridFill() method once more. Then pagination gets valid.

What could be the reason for GridView not paging for the first time?

Upvotes: 1

Views: 1191

Answers (1)

zkanoca
zkanoca

Reputation: 9918

If I change the order of the lines

//Page_Load()
gridFill();
GridView1.AllowPaging = true;
GridView1.PageSize = 10;

to

//Page_Load()
GridView1.AllowPaging = true;
GridView1.PageSize = 10;
gridFill();

it works. I can't believe it

Upvotes: 1

Related Questions