[asp.net] GridView - Show headers on empty data source

In C# how do I still show the headers of a gridview, even with the data source is empty.

I am not auto generating the columns as they are all predefined.

Currently what I am doing is the following.

Get a DataTable back from a stored procedure, then set the DataSource of the gridview, and then call DataBind().

This works fine when I have data, but when no rows are returned then I just get a blank spot where the grid should be.

Edit: Thanks all for the .NET 4+ property. I asked this back in the .NET 3.5 days. This is much easier now. :)

This question is related to asp.net gridview header

The answer is


Juste add ShowHeaderWhenEmpty property and set it at true

This solution works for me


I was using asp sqlDataSource. It worked for me when I set the CancelSelectOnNullParameter to false as below:

<asp:SqlDataSource ID="SqlData1" runat="server" ConnectionString="" SelectCommand="myStoredProcedure" SelectCommandType="StoredProcedure" CancelSelectOnNullParameter="False"> </asp:SqlDataSource>


set "<asp:GridView AutoGenerateColumns="false" ShowHeaderWhenEmpty="true""

showheaderwhenEmpty Property


You can set the ShowHeadersWhenNoRecords property of the ownertableview to true. aspx:

<asp:GridView ID="RadGrid2" runat="server" >       
<MasterTableView ShowHeadersWhenNoRecords="true"  > 

Also when the datasource for the GridView is null(when no records), you can try setting it as shown below: c#:

  if (GridView1.DataSource == null)  
  {  
        GridView1.DataSource = new string[] { };  
  } 
  GridView1.DataBind();

<asp:GridView ID="gvEmployee" runat="server"    
                 AutoGenerateColumns="False" ShowHeaderWhenEmpty=”True”>  
                    <Columns>  
                        <asp:BoundField DataField="Id" HeaderText="Id" />  
                        <asp:BoundField DataField="Name" HeaderText="Name" />  
                        <asp:BoundField DataField="Designation" HeaderText="Designation" />  
                        <asp:BoundField DataField="Salary" HeaderText="Salary"  />  
                    </Columns>  
                    <EmptyDataTemplate>No Record Available</EmptyDataTemplate>  
                </asp:GridView>  


in CS Page

gvEmployee.DataSource = dt;  
gvEmployee.DataBind();  

    <asp:GridView ID="gvEmployee" runat="server"    
                     AutoGenerateColumns="False" ShowHeaderWhenEmpty=”True”>  
                        <Columns>  
                            <asp:BoundField DataField="Id" HeaderText="Id" />  
                            <asp:BoundField DataField="Name" HeaderText="Name" />  
                            <asp:BoundField DataField="Designation" HeaderText="Designation" />  
                            <asp:BoundField DataField="Salary" HeaderText="Salary"  />  
                        </Columns>  
                        <EmptyDataTemplate>No Record Available</EmptyDataTemplate>  
                    </asp:GridView>  


    in CS Page

    gvEmployee.DataSource = dt;  
    gvEmployee.DataBind();  

Help.. see that link:
http://www.c-sharpcorner.com/UploadFile/d0e913/how-to-display-the-empty-gridview-in-case-of-no-records-in-d/

Use an EmptyDataTemplate like below. When your DataSource has no records, you will see your grid with headers, and the literal text or HTML that is inside the EmptyDataTemplate tags.

<asp:GridView ID="gvResults" AutoGenerateColumns="False" HeaderStyle-CssClass="tableheader" runat="server">
    <EmptyDataTemplate>
        <asp:Label ID="lblEmptySearch" runat="server">No Results Found</asp:Label>
    </EmptyDataTemplate>
    <Columns>
        <asp:BoundField DataField="ItemId" HeaderText="ID" />
        <asp:BoundField DataField="Description" HeaderText="Description" />
        ...
    </Columns>
</asp:GridView>

If you are working with ASP.NET 3.5 and lower, and your problem is relatively simple like mine, you can just return a null row from the SQL query.

if not exists (select RepId, startdate,enddate from RepTable where RepID= 10)
     select null RepID,null StartDate,null EndDate
else
     select RepId, startdate,enddate from RepTable where RepID= 10

This solution does not require any C# code or ASP.NET code

  1. Make sure you cast the null columns into appropriate names, otherwise it will not work.
  2. Else block must be included which is the same query as in if not exists (query part)
  3. In my case if I am using @RepID instead of 10. Which is mapped to a DropDownList box outside gridview.

Each time I change the drop down to select a different rep, Gridview is updated. If no record is found, it shows a null row.


    <asp:GridView ID="gvEmployee" runat="server"    
                     AutoGenerateColumns="False" ShowHeaderWhenEmpty=”True”>  
                        <Columns>  
                            <asp:BoundField DataField="Id" HeaderText="Id" />  
                            <asp:BoundField DataField="Name" HeaderText="Name" />  
                            <asp:BoundField DataField="Designation" HeaderText="Designation" />  
                            <asp:BoundField DataField="Salary" HeaderText="Salary"  />  
                        </Columns>  
                        <EmptyDataTemplate>No Record Available</EmptyDataTemplate>  
                    </asp:GridView>  


    in CS Page

    gvEmployee.DataSource = dt;  
    gvEmployee.DataBind();  

Help.. see that link:
http://www.c-sharpcorner.com/UploadFile/d0e913/how-to-display-the-empty-gridview-in-case-of-no-records-in-d/

set "<asp:GridView AutoGenerateColumns="false" ShowHeaderWhenEmpty="true""

showheaderwhenEmpty Property


Use an EmptyDataTemplate like below. When your DataSource has no records, you will see your grid with headers, and the literal text or HTML that is inside the EmptyDataTemplate tags.

<asp:GridView ID="gvResults" AutoGenerateColumns="False" HeaderStyle-CssClass="tableheader" runat="server">
    <EmptyDataTemplate>
        <asp:Label ID="lblEmptySearch" runat="server">No Results Found</asp:Label>
    </EmptyDataTemplate>
    <Columns>
        <asp:BoundField DataField="ItemId" HeaderText="ID" />
        <asp:BoundField DataField="Description" HeaderText="Description" />
        ...
    </Columns>
</asp:GridView>

After posting this I did come up with a way that works. However, I don't feel it is the best way to handle this. Any suggestions on a better one?

//Check to see if we get rows back, if we do just bind.

if (dtFunding.Rows.Count != 0)
{
    grdFunding.DataSource = dtFunding;
    grdFunding.DataBind();
}
else
{
  //Other wise add a emtpy "New Row" to the datatable and then hide it after binding.

     dtFunding.Rows.Add(dtFunding.NewRow());
     grdFunding.DataSource = dtFunding;
     grdFunding.DataBind();
     grdFunding.Rows[0].Visible = false;
}

I was just working through this problem, and none of these solutions would work for me. I couldn't use the EmptyDataTemplate property because I was creating my GridView dynamically with custom fields which provide filters in the headers. I couldn't use the example almny posted because I'm using ObjectDataSources instead of DataSet or DataTable. However, I found this answer posted on another StackOverflow question, which links to this elegant solution that I was able to make work for my particular situation. It involves overriding the CreateChildControls method of the GridView to create the same header row that would have been created had there been real data. I thought it worth posting here, where it's likely to be found by other people in a similar fix.


You can set the ShowHeadersWhenNoRecords property of the ownertableview to true. aspx:

<asp:GridView ID="RadGrid2" runat="server" >       
<MasterTableView ShowHeadersWhenNoRecords="true"  > 

Also when the datasource for the GridView is null(when no records), you can try setting it as shown below: c#:

  if (GridView1.DataSource == null)  
  {  
        GridView1.DataSource = new string[] { };  
  } 
  GridView1.DataBind();

I found a very simple solution to the problem. I simply created two GridViews. The first GridView called a DataSource with a query that was designed to return no rows. It simply contained the following:

    <Columns>
        <asp:TemplateField HeaderStyle-HorizontalAlign="Left">
            <HeaderTemplate>

               <asp:Label ID="lbl0" etc.>  </asp:Label>
               <asp:Label ID="lbl1" etc.>  </asp:Label>

            </HeaderTemplate>
        </asp:TemplateField>
    </Columns>

Then I created a div with the following characteristics and I place a GridView inside of it with ShowHeader="false" so that the top row is the same size as all the other rows.

<div style="overflow: auto; height: 29.5em; width: 100%">
    <asp:GridView ID="Rollup" runat="server" ShowHeader="false" DataSourceID="ObjectDataSource">
        <Columns>
            <asp:TemplateField HeaderStyle-HorizontalAlign="Left">
                <ItemTemplate>

               <asp:Label ID="lbl0" etc.>  </asp:Label>
               <asp:Label ID="lbl1" etc.>  </asp:Label>

                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
</div>

<asp:GridView ID="grdGroup"  EmptyDataText="No Records Found" ShowHeaderWhenEmpty="True" runat="server">

This is a basic example of Gridview with EmptyDataText and ShowHeaderWhenEmpty


You may use EmptyDataText as shown below:

<asp:GridView ID="_gridView" RunAt="server" AutoGenerateColumns="false"
          EmptyDataText="No entries found.">

It does not show headers, it renders your message "No entries found." instead.


<asp:GridView ID="grdGroup"  EmptyDataText="No Records Found" ShowHeaderWhenEmpty="True" runat="server">

This is a basic example of Gridview with EmptyDataText and ShowHeaderWhenEmpty


Use an EmptyDataTemplate like below. When your DataSource has no records, you will see your grid with headers, and the literal text or HTML that is inside the EmptyDataTemplate tags.

<asp:GridView ID="gvResults" AutoGenerateColumns="False" HeaderStyle-CssClass="tableheader" runat="server">
    <EmptyDataTemplate>
        <asp:Label ID="lblEmptySearch" runat="server">No Results Found</asp:Label>
    </EmptyDataTemplate>
    <Columns>
        <asp:BoundField DataField="ItemId" HeaderText="ID" />
        <asp:BoundField DataField="Description" HeaderText="Description" />
        ...
    </Columns>
</asp:GridView>

Juste add ShowHeaderWhenEmpty property and set it at true

This solution works for me


After posting this I did come up with a way that works. However, I don't feel it is the best way to handle this. Any suggestions on a better one?

//Check to see if we get rows back, if we do just bind.

if (dtFunding.Rows.Count != 0)
{
    grdFunding.DataSource = dtFunding;
    grdFunding.DataBind();
}
else
{
  //Other wise add a emtpy "New Row" to the datatable and then hide it after binding.

     dtFunding.Rows.Add(dtFunding.NewRow());
     grdFunding.DataSource = dtFunding;
     grdFunding.DataBind();
     grdFunding.Rows[0].Visible = false;
}

Use an EmptyDataTemplate like below. When your DataSource has no records, you will see your grid with headers, and the literal text or HTML that is inside the EmptyDataTemplate tags.

<asp:GridView ID="gvResults" AutoGenerateColumns="False" HeaderStyle-CssClass="tableheader" runat="server">
    <EmptyDataTemplate>
        <asp:Label ID="lblEmptySearch" runat="server">No Results Found</asp:Label>
    </EmptyDataTemplate>
    <Columns>
        <asp:BoundField DataField="ItemId" HeaderText="ID" />
        <asp:BoundField DataField="Description" HeaderText="Description" />
        ...
    </Columns>
</asp:GridView>

You may use EmptyDataText as shown below:

<asp:GridView ID="_gridView" RunAt="server" AutoGenerateColumns="false"
          EmptyDataText="No entries found.">

It does not show headers, it renders your message "No entries found." instead.


I was just working through this problem, and none of these solutions would work for me. I couldn't use the EmptyDataTemplate property because I was creating my GridView dynamically with custom fields which provide filters in the headers. I couldn't use the example almny posted because I'm using ObjectDataSources instead of DataSet or DataTable. However, I found this answer posted on another StackOverflow question, which links to this elegant solution that I was able to make work for my particular situation. It involves overriding the CreateChildControls method of the GridView to create the same header row that would have been created had there been real data. I thought it worth posting here, where it's likely to be found by other people in a similar fix.


You can use HeaderTemplate property to setup the head programatically or use ListView instead if you are using .NET 3.5.

Personally, I prefer ListView over GridView and DetailsView if possible, it gives you more control over your html.


After posting this I did come up with a way that works. However, I don't feel it is the best way to handle this. Any suggestions on a better one?

//Check to see if we get rows back, if we do just bind.

if (dtFunding.Rows.Count != 0)
{
    grdFunding.DataSource = dtFunding;
    grdFunding.DataBind();
}
else
{
  //Other wise add a emtpy "New Row" to the datatable and then hide it after binding.

     dtFunding.Rows.Add(dtFunding.NewRow());
     grdFunding.DataSource = dtFunding;
     grdFunding.DataBind();
     grdFunding.Rows[0].Visible = false;
}

You can use HeaderTemplate property to setup the head programatically or use ListView instead if you are using .NET 3.5.

Personally, I prefer ListView over GridView and DetailsView if possible, it gives you more control over your html.


Add this property to your grid-view : ShowHeaderWhenEmpty="True" it might help just check


I was using asp sqlDataSource. It worked for me when I set the CancelSelectOnNullParameter to false as below:

<asp:SqlDataSource ID="SqlData1" runat="server" ConnectionString="" SelectCommand="myStoredProcedure" SelectCommandType="StoredProcedure" CancelSelectOnNullParameter="False"> </asp:SqlDataSource>


You can use HeaderTemplate property to setup the head programatically or use ListView instead if you are using .NET 3.5.

Personally, I prefer ListView over GridView and DetailsView if possible, it gives you more control over your html.


Add this property to your grid-view : ShowHeaderWhenEmpty="True" it might help just check


You can use HeaderTemplate property to setup the head programatically or use ListView instead if you are using .NET 3.5.

Personally, I prefer ListView over GridView and DetailsView if possible, it gives you more control over your html.


If you are working with ASP.NET 3.5 and lower, and your problem is relatively simple like mine, you can just return a null row from the SQL query.

if not exists (select RepId, startdate,enddate from RepTable where RepID= 10)
     select null RepID,null StartDate,null EndDate
else
     select RepId, startdate,enddate from RepTable where RepID= 10

This solution does not require any C# code or ASP.NET code

  1. Make sure you cast the null columns into appropriate names, otherwise it will not work.
  2. Else block must be included which is the same query as in if not exists (query part)
  3. In my case if I am using @RepID instead of 10. Which is mapped to a DropDownList box outside gridview.

Each time I change the drop down to select a different rep, Gridview is updated. If no record is found, it shows a null row.


I found a very simple solution to the problem. I simply created two GridViews. The first GridView called a DataSource with a query that was designed to return no rows. It simply contained the following:

    <Columns>
        <asp:TemplateField HeaderStyle-HorizontalAlign="Left">
            <HeaderTemplate>

               <asp:Label ID="lbl0" etc.>  </asp:Label>
               <asp:Label ID="lbl1" etc.>  </asp:Label>

            </HeaderTemplate>
        </asp:TemplateField>
    </Columns>

Then I created a div with the following characteristics and I place a GridView inside of it with ShowHeader="false" so that the top row is the same size as all the other rows.

<div style="overflow: auto; height: 29.5em; width: 100%">
    <asp:GridView ID="Rollup" runat="server" ShowHeader="false" DataSourceID="ObjectDataSource">
        <Columns>
            <asp:TemplateField HeaderStyle-HorizontalAlign="Left">
                <ItemTemplate>

               <asp:Label ID="lbl0" etc.>  </asp:Label>
               <asp:Label ID="lbl1" etc.>  </asp:Label>

                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
</div>

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to gridview

Simple Android grid example using RecyclerView with GridLayoutManager (like the old GridView) Android Recyclerview GridLayoutManager column spacing Get the cell value of a GridView row add new row in gridview after binding C#, ASP.net Check if list is empty in C# How to refresh Gridview after pressed a button in asp.net Putting GridView data in a DataTable How to get row data by clicking a button in a row in an ASP.NET gridview Change header text of columns in a GridView Twitter Bootstrap and ASP.NET GridView No 'Access-Control-Allow-Origin' header in Angular 2 app How to add header row to a pandas DataFrame How can I make sticky headers in RecyclerView? (Without external lib) Adding header to all request with Retrofit 2 Python Pandas Replacing Header with Top Row Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers Pythonically add header to a csv file fatal error C1010 - "stdafx.h" in Visual Studio how can this be corrected? correct PHP headers for pdf file download How to fix a header on scroll