Friday, 4 June 2010

ASP.NET: Handing an empty Repeater control

The ASP.NET Repeater control is very useful and gives you lots of control over your output when compared to other controls such as the GridView. However, that comes at a cost of having to wire up all of your own events, sorting and paging etc.

Additionally, another drawback is that for a reason I can't explain, there is no EmptyDataTemplate or EmptyDataText property in a repeater which you can use when there are no items to display. Rumour abounded that ASP.NET 2.0 would include such a template, but it was not included.

Several people have tried different methods of handling this situation, but I found one which I think works nicely. I have a user control with a repeater in it, and on the Page_PreRender event I check that the Repeater's DataSource has rows in it. If not, then a label is made visible that tells the user no rows are present. If it does have data, then the Repeater is displayed.



<asp:Label ID="LabelNoProducts" runat="server" Text="You haven't added any products yet" visible="false" ></asp:Label>

Event: (User Control PreRender)

Private Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
Dim ds As DataTable = RepeaterProductsList.DataSource

If ds.Rows.Count = 0 Then
RepeaterProductsList.Visible = False
LabelNoProducts.Visible = True
RepeaterProductsList.Visible = True
LabelNoProducts.Visible = False
End If
End Sub

Et voila. Each time your user control is loaded, it checks if there are rows in the repeater, and lets the user know if not.