Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Bind List<string> into ListView in WebForms

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?

like image 749
rofans91 Avatar asked Apr 17 '12 06:04

rofans91


3 Answers

Use '<%# Container.DataItem %>:

<asp:Label ID="ProductNameLabel" runat="server" Text='<%# Container.DataItem %>'/>
like image 52
ionden Avatar answered Nov 14 '22 16:11

ionden


<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.

like image 1
Dave Avatar answered Nov 14 '22 16:11

Dave


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

like image 1
Tanzeel ur Rehman Avatar answered Nov 14 '22 16:11

Tanzeel ur Rehman