I have a List<string>
collection that I would like to bind into my ListView
.
Below is the markup for my ListView
:
<asp:ListView ID="lvList" runat="server">
<LayoutTemplate>
<div id="Div1" runat="server">
<div ID="itemPlaceholder" runat="server">
</div>
</div>
</LayoutTemplate>
<EmptyDataTemplate>
<div id="Div2" runat="server">
<div ID="itemPlaceholder" runat="server">
No data was returned.
</div>
</div>
</EmptyDataTemplate>
<ItemTemplate>
<asp:Label ID="ProductNameLabel" runat="server" Text='<%# Eval ("theList") %>'/>
</ItemTemplate>
</asp:ListView>
in my CodeBehind:
protected void Page_Load(object sender, EventArgs e)
{
List<string> theList = new List<string>();
//populate members of list
lvList.DataSource = theList;
lvList.DataBind();
}
Error Message:
System.Web.HttpException was unhandled by user code
Message="DataBinding: 'System.String' does not contain a property with the name 'theList'."
I think I am doing things wrongly here, can someone advise me pls?
Use '<%# Container.DataItem %>
:
<asp:Label ID="ProductNameLabel" runat="server" Text='<%# Container.DataItem %>'/>
<asp:Label ID="ProductNameLabel" runat="server" Text='<%# Eval ("theList") %>
this line is causing the problem because you are refering to the property 'theList' within the current element of the list but the list does not have any properties except the strings inside.
The way to go would be for example implementation of the method in the code behind e.g.
protected void Test(object obj)
{
return obj.ToString();
}
and in the aspx:
<asp:Label ID="ProductNameLabel" runat="server" Text='<%# Test(Container.DataItem) %>
I haven't tested it but it should do the trick.
EVAL is used on single key value, the data bound control iterates through the collection from start to end and place one by one on the place where you have place the eval statement.
The answer in this link can deliver better idea. How to retrieve current object from collections using DataBinder.Eval?
Hope this will help
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With