Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ListView LayoutTemplate does not show when empty asp.net

I have an <asp:ListView> but for some reason the LayoutTemplate section does not show when the list is empty, although the <EmptyDataTemplate> section shows. The LayoutTemplate contains the headers for the table, and I want to show an empty table when there are no items in the datasource, not just the content of EmptyDataTemplate.

If there is no choice I will copy the LayoutTemplate into EmptyDataTemplate but it seems stupid to have to do this. Ideas?

like image 496
NibblyPig Avatar asked Mar 31 '11 13:03

NibblyPig


2 Answers

From the MSDN:

The empty template is displayed in a ListView control when the data source that is bound to the control does not contain any records and the InsertItemPosition property is set to InsertItemPosition.None. The template is rendered instead of the LayoutTemplate template. If the InsertItemPosition property is set to a value other than InsertItemPosition.None, the EmptyDataTemplate template is not rendered.

the key words here are "...the template is rendered instead of the LayoutTemplate template..."

So I think, you have to copy the LayoutTemplate into the EmptyDataTemplate template.

like image 139
Oleks Avatar answered Oct 03 '22 11:10

Oleks


In a very simple way you can get both your headers and a message saying that there were no data.

You make your LayoutTemplate like the following idea:

<LayoutTemplate>
  <table>
    <tr>
      <td>a header</td>
      <td>another header</td>
      <td>third header</td>
    </tr>
    <tr runat="server" id="itemPlaceholder">
      <td colspan="3"
        There is no data!
      </td>
    </tr>
  </table>
</LayoutTemplate>

Notice that the tr that is the placeholder (marked by id="itemPlaceholder") actually contains something. It contains what should be shown when there is no data. Then, in code behind, you set the <EmptyTemplate> to be equal to the <LayoutTemplate> (so that you have only one such template to maintain). I do it like this:

Private Sub lvwThings_Init(sender As Object, e As EventArgs) Handles lvwThings.Init
    lvwThings.EmptyDataTemplate = lvwThings.LayoutTemplate
End Sub

The logic then is as follows:

When there is data, i.e. when the actual <LayoutTemplate> is used, the whole <tr runat="server" id="itemPlaceholder">, with the td and text it contains, will be replaced by the <ItemTemplate>.

But, when there is no data, i.e. when the <EmptyTemplate> is used (instead of the <LayoutTemplate>), nothing inside the <EmptyTemplate>is replaced, so everything is shown as it is.

like image 34
Magnus Avatar answered Oct 03 '22 12:10

Magnus