0

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.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Roberts
  • 53
  • 1
  • 7
  • You can use Query to check the table child element and whenever it has less than then row you can append additional rows to it.... if you want to.. – Learning Jun 26 '19 at 11:00

1 Answers1

0

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();  
}
Mangesh Auti
  • 1,123
  • 1
  • 7
  • 12