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.
C
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.
Add this property to your grid-view : ShowHeaderWhenEmpty="True" it might help just check
<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.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()
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
if not exists (query part)
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.
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.