Categories
ASP.net VB.net

Adding EmptyDataTemplate to Repeater and TreeView

The GridView control contains an EmptyDataTemplate property to display alternative content when the data source is empty. However, other data bound controls such as Repeater and TreeView do not have this property. We can add this functionality to existing data bound controls by:

  1. subclassing the existing data bound control,
  2. adding the EmptyDataTemplate property, and
  3. overriding the Render event to conditionally render the EmptyDataTemplate if the data source is empty and the EmptyDataTemplate property is specified.

Let’s create MyRepeater using these steps:

Imports System.ComponentModel
Imports System.Web.UI

''' <summary>
''' Adds <b>EmptyDataTemplate</b> property.
''' </summary>
Public Class MyRepeater
	Inherits WebControls.Repeater
	Implements INamingContainer

	<BrowsableAttribute(False)>
	<PersistenceMode(PersistenceMode.InnerProperty)>
	<TemplateContainer(GetType(MyRepeater))>
	Public Overridable Property EmptyDataTemplate() As ITemplate

	Protected Overrides Sub Render(writer As HtmlTextWriter)
		If Items.Count = 0 AndAlso EmptyDataTemplate IsNot Nothing Then
			Dim container As New Control()
			EmptyDataTemplate.InstantiateIn(container)
			container.RenderControl(writer)
		Else
			MyBase.Render(writer)
		End If
	End Sub
End Class

Items.Count is used to check whether the data source is empty for the Repeater control. We can create MyTreeView in a similar way:

Imports System.ComponentModel
Imports System.Web.UI

''' <summary>
''' Adds <b>EmptyDataTemplate</b> property.
''' </summary>
Public Class MyTreeView
	Inherits WebControls.TreeView
	Implements INamingContainer

	<BrowsableAttribute(False)>
	<PersistenceMode(PersistenceMode.InnerProperty)>
	<TemplateContainer(GetType(MyTreeView))>
	Public Overridable Property EmptyDataTemplate() As ITemplate

	Protected Overrides Sub Render(writer As HtmlTextWriter)
		If Nodes.Count = 0 AndAlso EmptyDataTemplate IsNot Nothing Then
			Dim container As New Control()
			EmptyDataTemplate.InstantiateIn(container)
			container.RenderControl(writer)
		Else
			MyBase.Render(writer)
		End If
	End Sub
End Class

Nodes.Count is used to check the TreeView control instead.

Finally, substitute <asp:Repeater> or <asp:TreeView> with new MyRepeater or MyTreeView controls, add the EmptyDataTemplate property and voilĂ , you can now specify your own custom message when the data source is empty.

VarsÄgod!

Thanks to:

Leave a Reply