Show asp.net Gridview Header when no data/records found


By setting the inbuilt properties of Gridview ShowHeaderWhenEmpty="true" and EmptyDataText="No data found message here." We can show the Gridview Header and the custom message when there is no records in the result set which we are binding to the grid.


The following example will generate the above output.


ShowHeader.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ShowHeader.aspx.cs" Inherits="ShowHeader" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div style="padding:50px;"> <asp:GridView ID="gvSample" runat="server" CellPadding="5" BorderStyle="Ridge" ShowHeaderWhenEmpty="true" EmptyDataText="No Records Found." EmptyDataRowStyle-ForeColor="Red"> <HeaderStyle BackColor="#272457" ForeColor="White" /> </asp:GridView> </div> </form> </body> </html>

ShowHeader.aspx.cs

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; public partial class ShowHeader : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { try { if (!IsPostBack) FillGrid(); } catch { } } void FillGrid() { try { DataSet ds = GetResultSet(); gvSample.DataSource = ds; gvSample.DataBind(); } catch { throw; } } DataSet GetResultSet() { try { //change this code to get the result set from you DB. DataSet ds = new DataSet(); DataTable dt = new DataTable(); dt.Columns.Add("Employee ID"); dt.Columns.Add("Employee Name"); dt.Columns.Add("Department"); dt.Columns.Add("Salary"); ds.Tables.Add(dt); return ds; } catch { throw; } } }