Thursday, July 23, 2009

Handling Empty Data in an ASP.NET Repeater control

In the <FooterTemplate>, add a Label with some empty data text and set its visible property to false.

<FooterTemplate>

 <tr>

 <td>

 <asp:Label
ID="lblEmptyData"

        Text="No Data To Display"
runat="server"
Visible="false">

 </asp:Label>

 </td>

 </tr>

 </table>           

 </FooterTemplate>

Now add an ItemDataBound event to the Repeater

<asp:Repeater
ID="Repeater1"
runat="server"
DataSourceID="SqlDataSource1"            

    onitemdatabound="Repeater1_ItemDataBound">

In the code behind, write the following code:

C#

    protected
void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)

    {

        if (Repeater1.Items.Count < 1)

        {

            if (e.Item.ItemType == ListItemType.Footer)

            {

                Label lblFooter = (Label)e.Item.FindControl("lblEmptyData");

                lblFooter.Visible = true;

            }

        }

    }

The code checks if the Repeater has items in it. If the items count is less than 1, the code uses the FindControl() to locate the label and set it to visible.

On running the application again, you get to see the message 'No Data To Display' as shown in the screenshot below. This is certainly more user friendly than letting the user wonder why the data was not displayed at the first place.

0 comments: