DotNet Mirror
  DNM facebook   DNM Google+   DNM Twitter   

ASP.NET GridView - Displaying custom paging summary in footer and setting fixed height when less number of rows in page or no data to dispaly

By Ashok Nalam on 14 May 2013 | Category: ASP.NET | Tagged: control gridview paging 
This article resolves how to set fixed height for GridView dynamically when there are less number of rows in a page or on empty data and displaying custom paging summary on pager template of GridView.
  Discuss Add Comment   |  
Add rating Rate this resource   

Issue

In general for ASP.NET GridView control, it is bit difficult to handle

  • Fixed height when the number of rows are less in a page or when there is no data to display.
  • showing custom paging summary like showing 1-10 of 100 records

In this article, we tried to address both the issues using below code.

Code:

FixedHeightGridViewEvenForLessRows.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FixedHeightGridViewEvenForLessRows.aspx.cs" Inherits="FixedHeightGridViewEvenForLessRows" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>GridView Fixed Height and Custom Paging</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:GridView ID="gvStudent" runat="server" Width="600px" AutoGenerateColumns="false"
                AllowPaging="true" OnPageIndexChanging="gridOfficalDocs_PageIndexChanging"
                OnDataBound="gridOfficalDocs_DataBound" ShowHeaderWhenEmpty="true" EmptyDataText="No records Found to Display!">
                <HeaderStyle Height="35px" BackColor="YellowGreen" />
                <FooterStyle Height="50px" />
                <RowStyle Height="20px" BackColor="#89EDB9" />
                <AlternatingRowStyle Height="20px" BackColor="#EA8F64" />
                <Columns>
                    <asp:BoundField HeaderText="Roll No" DataField="rollno" />
                    <asp:BoundField HeaderText="Full Name" DataField="fullname" />
                    <asp:BoundField HeaderText="Gender" DataField="gender" />
                </Columns>
                <PagerSettings Mode="Numeric" />
                <PagerStyle VerticalAlign="Bottom" />
                <EmptyDataRowStyle HorizontalAlign="Center" VerticalAlign="Top" />
            </asp:GridView>
        </div>
    </form>
</body>
</html>

FixedHeightGridViewEvenForLessRows.aspx.cs

using System;
using System.Data;
using System.Text;
using System.Web.UI.WebControls;

public partial class FixedHeightGridViewEvenForLessRows : System.Web.UI.Page
{
    public int totalRowCount = 0;
    public int pageSize = 10;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            gvStudent.PageSize = pageSize;
            BindGrid();
        }
    }

    protected DataTable GetData()
    {
        //create sample data here
        DataTable dt = new DataTable();
        DataColumn dcRollNo = new DataColumn("rollno");
        DataColumn dcName = new DataColumn("fullname");
        DataColumn dcGender = new DataColumn("gender");
        dt.Columns.Add(dcRollNo);
        dt.Columns.Add(dcName);
        dt.Columns.Add(dcGender);
        for (int i = 1; i <= 12; i++)
        {
            DataRow dr = dt.NewRow();
            dr["rollno"] = i.ToString();
            if (i % 2 == 0) //odd row
            {
                dr["fullname"] = "Ramu";
                dr["gender"] = "Male";
            }
            else //Even row
            {
                dr["fullname"] = "Sita";
                dr["gender"] = "Female";
            }
            dt.Rows.Add(dr);
        }
        totalRowCount = dt.Rows.Count; //assign total count
        return dt;
    }

    public void BindGrid()
    {
        gvStudent.DataSource = GetData(); ;
        gvStudent.DataBind();
    }

    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
        SetFixedHeightForGridIfRowsAreLess(gvStudent);
    }

    public void SetFixedHeightForGridIfRowsAreLess(GridView gv)
    {
        double headerFooterHeight = gv.HeaderStyle.Height.Value + 35; //we set header height style=35px and there no footer  height so assume footer also same
        double rowHeight = gv.RowStyle.Height.Value;
        int gridRowCount = gv.Rows.Count;
        if (gridRowCount <= gv.PageSize)
        {
            double height = (gridRowCount * rowHeight) + ((gv.PageSize - gridRowCount) * rowHeight) + headerFooterHeight;
            //adjust footer height based on white space removal between footer and last row
            height += 40;
            gv.Height = new Unit(height);
        }
    }

    protected void gridOfficalDocs_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvStudent.PageIndex = e.NewPageIndex;
        BindGrid();
    }

    protected void gridOfficalDocs_DataBound(object sender, EventArgs e)
    {
        createPagingSummaryOnPagerTemplate(sender, totalRowCount, pageSize);
    }

    public void createPagingSummaryOnPagerTemplate(object sender, int totalCount, int pageSize)
    {
        GridView gv = sender as GridView;
        if (gv != null)
        {
            //Get Bottom Pager Row from a gridview
            GridViewRow row = gv.BottomPagerRow;

            if (row != null)
            {
                //create new cell to add to page strip
                TableCell pagingSummaryCell = new TableCell();
                pagingSummaryCell.Text = DisplayCusotmPagingSummary(totalCount, gv.PageIndex, pageSize);
                pagingSummaryCell.HorizontalAlign = HorizontalAlign.Right;
                pagingSummaryCell.VerticalAlign = VerticalAlign.Middle;
                pagingSummaryCell.Width = Unit.Percentage(100);
                pagingSummaryCell.Height = Unit.Pixel(35);
                //Getting table which shows PagingStrip
                Table tbl = (Table)row.Cells[0].Controls[0];

                //BottomPagerRow will be visible false if pager doesn't have numbers and page number 1 will be displayed
                if (totalCount <= pageSize)
                {
                    gv.BottomPagerRow.Visible = true;
                    tbl.Rows[0].Cells.Clear();
                    tbl.Width = Unit.Percentage(100);
                }
                //Find table and add paging summary text
                tbl.Rows[0].Cells.Add(pagingSummaryCell);
                //assign header row color to footer row
                tbl.BackColor = System.Drawing.ColorTranslator.FromHtml("#1AD9F2");
                tbl.Width = Unit.Percentage(100);
            }
        }
    }

    public static string DisplayCusotmPagingSummary(int numberOfRecords, int currentPage, int pageSize)
    {
        StringBuilder strDisplaySummary = new StringBuilder();
        int numberOfPages;
        if (numberOfRecords > pageSize)
        {
            // Calculating the total number of pages
            numberOfPages = (int)Math.Ceiling((double)numberOfRecords / (double)pageSize);
        }
        else
        {
            numberOfPages = 1;
        }
        strDisplaySummary.Append("Showing ");
        int floor = (currentPage * pageSize) + 1;
        strDisplaySummary.Append(floor.ToString());
        strDisplaySummary.Append("-");
        int ceil = ((currentPage * pageSize) + pageSize);

        if (ceil > numberOfRecords)
        {
            strDisplaySummary.Append(numberOfRecords.ToString());
        }
        else
        {
            strDisplaySummary.Append(ceil.ToString());
        }

        strDisplaySummary.Append(" of ");
        strDisplaySummary.Append(numberOfRecords.ToString());
        strDisplaySummary.Append(" results ");
        return strDisplaySummary.ToString();
    }
}

Output:

GridView Page1

GridView Page2

From the output, we can observe

  •  GridView Page2 image has only two rows but the grid height is same as GridView Page1 image.
  •  Custom paging summary (Showing 1-10 of 12 results ) on right side of footer.

Showing fixed GridView height when there is no data to display:

From the code behind file, if we comment one line(//dt.Rows.Add(dr);) then Data Table will not return any data and output looks like

Hope this solves your issue!

  Discuss Add Comment    
Add rating Rate this resource   
About the Contributor
Member Since : 10 Dec 2012
Member Points (Level) : 9226  (Professional)
Location : INDIA
Home Page : http://dotnetmirror.com
About : I am admin of this site.
Rate this resource
 
Add your Comment
Name Email WebSite
Captcha Refresh


Comments (2)
 
1. By Prashant Dikonda on 14 Jun 2013

this is good post ,lots help for me,but it is not working in IE

 
2. By Ashok Nalam on 14 Jun 2013

Thanks. can you please tell me what is the issue with IE.

 
cheap jordans|wholesale air max|wholesale jordans|wholesale jewelry|wholesale jerseys