Extended asp:Repeater
I've always wished for a Repeater with a NoData template. It is a very common requirement that we display a “No data available” message when a database query returned no rows. Now I have finally got around to writing this very simple extension:
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace alexcampbell.Controls
{
/// <summary>
/// An asp:Repeater control that lets you specify a template to be shown if there is no data in the repeater
/// </summary>
public class ExtendedRepeater : Repeater
{
private ITemplate _noDataTemplate;
public ITemplate NoDataTemplate {
get {
return _noDataTemplate;
}
set {
_noDataTemplate = value;
}
}
protected override void OnDataBinding(EventArgs e) {
base.OnDataBinding (e);
if(this.Items.Count == 0) {
NoDataTemplate.InstantiateIn(this);
}
}
}
}
You can use this control on a web form like this:
<%@ Register TagPrefix=”AlexCampbell” Namespace=”alexcampbell.Controls” Assembly=”alexcampbell” %>
<AlexCampbell:ExtendedRepeater>
<ItemTemplate>
<%# Container.DataItem %>
</ItemTemplate>
<NoDataTemplate>
No data returned!
</NoDataTemplate>
</AlexCampbell:ExtendedRepeater>