Today I had to find a way to force x number of rows on a GridView. The problem is that if the GridView.PageSize is larger than the number of rows you are data binding, the GridView itself gets smaller in the height. You often see it when paging through the pages of a grid. The last page is always shorter than the rest, because there are fewer rows. That is usually not a issue, but I had to keep our designers happy.

It is actually pretty simple in a class that inherits from System.Web.UI.WebControls.GridView. Just override the OnDataBound method and add the extra rows. In this example, the number of rows is always the same as the PageSize property and still keeping the footer row at the bottom.

protected override void OnDataBound(EventArgs e)
{
 GridViewRow gvRow = null;

 for (int rows = this.Rows.Count; rows < this.PageSize; rows++)
 {
  gvRow = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Normal);

  for (int columns = 0; columns < this.Columns.Count; columns++)
  {
   gvRow.Controls.Add(new TableCell());
  }

  //Inserts the rows right above the footer row.
  //Remove the "- 1" if you are not using a footer.
  this.Controls[0].Controls.AddAt(this.Controls[0].Controls.Count - 1, gvRow);
 }
}

Comments


Comments are closed