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

GridView - Show headers on empty data source


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


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.