简体   繁体   English

如何绑定列表 <string> 到WebForms中的ListView

[英]How to Bind List<string> into ListView in WebForms

I have a List<string> collection that I would like to bind into my ListView . 我有一个List<string>集合,我想绑定到我的ListView

Below is the markup for my ListView : 下面是我的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: 在我的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 用户代码未处理System.Web.HttpException
Message="DataBinding: 'System.String' does not contain a property with the name 'theList'." Message =“DataBinding:'System.String'不包含名为'theList'的属性。”

I think I am doing things wrongly here, can someone advise me pls? 我想我在这里做错了,有人可以告诉我吗?

使用'<%# 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. 此行导致问题,因为您在列表的当前元素中引用属性'theList',但列表除了内部的字符串之外没有任何属性。

The way to go would be for example implementation of the method in the code behind eg 要走的路是例如在后面的代码中实现方法

protected void Test(object obj)
{
    return obj.ToString();
}

and in the aspx: 在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. EVAL用于单个键值,数据绑定控件从头到尾遍历集合,并逐个放置在放置eval语句的位置。

The answer in this link can deliver better idea. 这个链接的答案可以带来更好的想法。 How to retrieve current object from collections using DataBinder.Eval? 如何使用DataBinder.Eval从集合中检索当前对象?

Hope this will help 希望这会有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM