Mikee
Mikee

Reputation: 646

ASP.NET ListView - How to set EmptyDataTemplate programmatically?

I have a class MyListView, it inherits from ASP.NET ListView. I would like to implement a default behaviour - if a programmer doesn't specify EmptyDataTemplate in aspx code, the MyListView will use a predefined default template (class MyEmptyDataTemplate).

What I have tried is this:

public class MyListView : ListView
{
    protected override void CreateChildControls()
    {
        if (EmptyDataTemplate == null)
            EmptyItemTemplate = new MyEmptyDataTemplate();

        base.CreateChildControls();                         
    }
}

The MyEmptyDataTemplate implements ITemplate interface. The problem is, that InstantiateIn() method of the MyEmptyDataTemplate is never called, and my default template never appears in case there are no records in datasource. Apparently I wrong understand the ListView component lifecycle and template should be set somewhere else.

Upvotes: 2

Views: 1263

Answers (1)

Adrian Iftode
Adrian Iftode

Reputation: 15673

Try to do this on the Init event:

public class MyListView : ListView
{
    public MyListView()
    {
       this.Init += (o, e) =>
            { 
                if (EmptyDataTemplate == null)
                     EmptyDataTemplate = new MyEmptyDataTemplate();
            };
    }
}

edit After checking this again I realized that EmptyDataTemplate was checked if emtpy, but the template which has been assigned is EmptyItemTemplate. However both methods are good to instantiate the templates..

Upvotes: 2

Related Questions