A Repeater is one of the lightest data bound controls in ASP.NET. It’s certainly faster than heavier controls like a GridView, however, its performance comes with a price. Its missing most of the functionality you can find in other controls. There is no built in paging or even a UI at all. It does provide some templates to place your HTML in, but that’s it.
If you need to display a message to the user when the Repeater is empty, something in the style of: "No results have been found" or "Your shopping cart is empty" just like EmptyDataTemplate in a GridView, you will need to add a new element, maybe a Label, to the page and check your Repeater. Then you would most likely have to set it to be invisible on the page while you show the user an empty results message. Another option is to inject this message into the repeater itself using an ITemplate.
An ITemplate defines the Control object that child controls and templates belong to. These child controls are in turn defined within the template.
Let’s start by defining our template
sealed class EmptyTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
Literal l = new Literal();
l.Text = "Empty";
container.Controls.Add(l);
}
}
Then showing the Repeater on the page and using its onprerender to check for empty results.
<asp:Repeater ID="Repeater1" runat="server" onprerender="Repeater1_PreRender"></asp:Repeater>
Finally, when we encounter no results, we are going to show the EmptyTemplate
protected void Repeater1_PreRender(object sender, EventArgs e)
{
if (Repeater1.Items.Count > 0)
return;
ITemplate emptyTemplate = null;
emptyTemplate = new EmptyTemplate();
emptyTemplate.InstantiateIn(Repeater1);
Repeater1.ItemTemplate = emptyTemplate;
}
That’s it. Our Repeater will now show the EmptyTemplate when it contains no items.
Posted
13 Feb 2010 6:48 AM
by
Gal Ratner