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