Last week I was working on a news archive, and i wanted to display the results in a listview. I decided to use the ASP.Net 3.5 ListView, but for some reason, I couldn't get it to work. Although I am a experienced "googler" (or googlar?!) I really couldn't find any solution on the error's that I got while trying to add this Control.
These were the problems that i Encountered and it's solutions.
I added the ListView in code and added the following ItemTemplate:
<%@ Control Language="C#" %>
<li>
<asp:Label ID="DateLabel" runat="Server" Text='<%# Eval("Date")%>' />
</li>
WHen trying to load the page, i Got thje following error:
Exception Details: System.InvalidOperationException: Databinding methods such as Eval(), XPath(), and Bind() can only be used in controls contained in a page.
Well, as the exception tells: the Eval function isnt allowed to be used in a template, so i decided to use the DataBinder method:
<%@ Control Language="C#" %>
<li>
<asp:Label ID="DateLabel" runat="Server" Text='<%# DataBinder.Eval(Container, "Date")%>' />
</li>
It throwed the followin exception:
DataBinding: 'System.Web.UI.WebControls.ListViewDataItem' does not contain a property with the name 'Date'.
After that, I realised myself that I shouldn't use the conainter, but the DataItem of the container, so I modified my template:
<%@ Control Language="C#" %>
<li>
<asp:Label ID="DateLabel" runat="Server" Text='<%# DataBinder.Eval(Container.DataItem, "Date")%>' />
</li>
this template throws an compilation error: Compiler Error Message: CS0117: 'System.Web.UI.Control' does not contain a definition for 'DataItem'. And why? We are using the ASP.Net 3.5 listview control, so there is a chance that namespace is extended with thte DataItem. So I tried to cast the DataItem to the specific ListViewDataItem:
<%@ Control Language="C#" %>
<li>
<asp:Label ID="DateLabel" runat="Server" Text='<%# DataBinder.Eval(((System.Web.UI.WebControls.ListViewDataItem)(Container)).DataItem, "Date", "{0:dd-MM-yyyy}")%>' />
</li>
I was sure that I was Another step closer to the solution. Hitting F5 in my browser got the the following exception:
Compiler Error Message: CS0234: The type or namespace name 'ListViewDataItem' does not exist in the namespace 'System.Web.UI.WebControls' (are you missing an assembly reference?)
After adding the Assembly for the asp.net 3.5 ListView, I got the following code:
<%@ Control Language="C#" %>
<%@Assembly Name="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<li>
<asp:Label ID="DateLabel" runat="Server" Text='<%# DataBinder.Eval(((System.Web.UI.WebControls.ListViewDataItem)(Container)).DataItem, "Date", "{0:dd-MM-yyyy}")%>' />
</li>
A last refresh of my browser made me happy: no error's and a nice, working asp.net 3.5 ListView.