How to Set Last Row Data Paging

163 views Asked by At

I have trouble to set last row for paging.

I set Page size: 10 in gridview

This my behind code:

protected void Page_Load(object sender, EventArgs e)
    {
        BindData();
    }

    public void BindData()
    {
        string strConnection = @"Data Source=.\sa;Initial Catalog=Northwind;Integrated Security=SSPI;";

        SqlConnection con = new SqlConnection(strConnection);
        con.Open();
        SqlCommand cmd = new SqlCommand("select ProductId, ProductName, SupplierId from Products", con);
        DataSet ds = new DataSet();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
        con.Close();  

    }

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        BindData();  
    }

The Result:

The page 7 have 10 rows

but after I change page 7 to last page have only less than 10 rows.

I want the last page have 10 rows although data table 7 rows

anybody can improve my code.

1

There are 1 answers

1
Mangesh Auti On

You need to add Empty row in the Dataset.table (No of a row to add it depends on how many rows less than the page size)

protected void Page_Load(object sender, EventArgs e)
    {
        BindData();
    }

public void BindData()
{
    string strConnection = @"Data Source=.\sa;Initial Catalog=Northwind;Integrated Security=SSPI;";

    SqlConnection con = new SqlConnection(strConnection);
    con.Open();
    SqlCommand cmd = new SqlCommand("select ProductId, ProductName, SupplierId from Products", con);
    DataSet ds = new DataSet();
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    da.Fill(ds);
    int rowcount = ds.Tables[0].Rows.Count;
    int remainingCount = 10 - (rowcount % 10);
    for (int i = 0; i < remainingCount; i++)
    {
        DataRow row = ds.Tables[0].NewRow();
        ds.Tables[0].Rows.Add(row);
    }
    GridView1.DataSource = ds;
    GridView1.DataBind();
    con.Close();  

}

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    GridView1.PageIndex = e.NewPageIndex;
    BindData();  
}