80

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. :)

Joshua Hudson
  • 2,187
  • 2
  • 20
  • 24

16 Answers16

144

ASP.Net 4.0 added the boolean ShowHeaderWhenEmpty property.

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.showheaderwhenempty.aspx


<asp:GridView runat="server" ID="GridView1" ShowHeaderWhenEmpty="true" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField HeaderText="First Name" DataField="FirstName" />
        <asp:BoundField HeaderText="Last Name" DataField="LastName" />
    </Columns>
</asp:GridView>

Note: the headers will not appear unless DataBind() is called with something other than null.

GridView1.DataSource = New List(Of String)
GridView1.DataBind()
zacharydl
  • 4,278
  • 1
  • 29
  • 23
35

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;
}
Joshua Hudson
  • 2,187
  • 2
  • 20
  • 24
5

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.

ciencia
  • 456
  • 4
  • 11
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
4

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.

TheTechGuy
  • 16,560
  • 16
  • 115
  • 136
  • Thanks Hammad Khan. This worked for us. I've read dozens of threads on this and this is the only occurence of this SQL-only (or SQL-mainly - I'll need to hide the null row) approach I have come across. More importantly for us: it causes the footer to be displayed too, which is a harder problem than displaying the headers. :) – Zeek2 Dec 17 '19 at 09:54
  • 1
    Glad that it worked for you, rather simple solution:) – TheTechGuy Dec 21 '19 at 03:44
3

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

showheaderwhenEmpty Property

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
2

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.

Liwen
  • 937
  • 10
  • 12
2

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();
kez
  • 2,273
  • 9
  • 64
  • 123
1

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

tariq
  • 2,193
  • 15
  • 26
1

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>
anegin
  • 11
  • 1
1
<asp:GridView ID="grdGroup"  EmptyDataText="No Records Found" ShowHeaderWhenEmpty="True" runat="server">

This is a basic example of Gridview with EmptyDataText and ShowHeaderWhenEmpty

Bartłomiej Mucha
  • 2,762
  • 1
  • 30
  • 36
1

Juste add ShowHeaderWhenEmpty property and set it at true

This solution works for me

onlyme
  • 3,776
  • 2
  • 23
  • 17
0

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>

-1
<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();  
-2

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.

biegleux
  • 13,179
  • 11
  • 45
  • 52
  • 2
    This is not exactly what I asked for. I was looking for a way to show an empty grid, WITH headers. I know I could of always used EmptyDataText but my requirements specifically called for an empty grid, with headers, if no data existed. – Joshua Hudson Oct 11 '12 at 17:58
-2
    <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/
Suresh klt
  • 59
  • 1
  • 3
-3

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>