6

我有一个List<string>想要绑定到我的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>

在我的代码隐藏中:

protected void Page_Load(object sender, EventArgs e)
{         
    List<string> theList = new List<string>();
    //populate members of list
    lvList.DataSource = theList;
    lvList.DataBind();
}

错误信息:

System.Web.HttpException 未被用户代码处理
Message="DataBinding: 'System.String' 不包含名为 'theList' 的属性。"

我想我在这里做错了,有人可以告诉我吗?

4

3 回答 3

13

使用'<%# Container.DataItem %>

<asp:Label ID="ProductNameLabel" runat="server" Text='<%# Container.DataItem %>'/>
于 2012-04-17T06:13:09.283 回答
1

<asp:Label ID="ProductNameLabel" runat="server" Text='<%# Eval ("theList") %>

此行导致问题,因为您在列表的当前元素中引用属性“theList”,但列表除了里面的字符串之外没有任何属性。

例如,要在后面的代码中实现该方法,例如

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

在 aspx 中:

 <asp:Label ID="ProductNameLabel" runat="server" Text='<%# Test(Container.DataItem) %>

我还没有测试过它,但它应该可以解决问题。

于 2012-04-17T06:13:14.640 回答
1

EVAL 用于单个键值,数据绑定控件从头到尾遍历集合,并在放置 eval 语句的位置一一放置。

此链接中的答案可以提供更好的想法。 如何使用 DataBinder.Eval 从集合中检索当前对象?

希望这会有所帮助

于 2012-04-17T06:28:25.157 回答