asp.netgridviewasp.net-2.0

Optionally display a text in place of GridView when the GridView has no rows


I have a basic GridView that displays a list of tasks to do (just an example)

<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" AllowSorting="True" >
    <Columns>
        <asp:BoundField DataField="todo" HeaderText="To Do" ReadOnly="True" SortExpression="todo" />
        <asp:BoundField DataField="byDate" HeaderText="By When" ReadOnly="True"

SortExpression="byDate" />

the data source is specified within the aspx page and it is a result set from a stored procedure

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="..."
      SelectCommand="pToDoList" SelectCommandType="StoredProcedure">
</asp:SqlDataSource>

So the rendered page presents tasks as rows of data (a row per task)

My question is

When there is not data returned by stored procedure the page remains blank. I would like to have a text instead saying for example: "nothing to do today"

How to do that? Thank you


Solution

  • Use the EmptyDataTemplate:

    <asp:gridview id="CustomersGridView" 
            datasourceid="CustomersSqlDataSource" 
            autogeneratecolumns="true"
            runat="server">
            
            <emptydatarowstyle backcolor="LightBlue"
              forecolor="Red"/>
                        
            <emptydatatemplate>
                    
              <asp:image id="NoDataImage"
                imageurl="~/images/Image.jpg"
                alternatetext="No Image" 
                runat="server"/>
                            
                No Data Found.  
                    
            </emptydatatemplate> 
                    
     </asp:gridview>
    

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