c# - 将 struct 类型的通用列表绑定(bind)到 Repeater

标签 c# asp.net list repeater generics

我在尝试将通用列表绑定(bind)到中继器时遇到了一些问题。泛型列表中使用的类型实际上是一个结构。

我在下面构建了一个基本示例:

struct Fruit
{
    public string FruitName;
    public string Price;    // string for simplicity.
}


protected void Page_Load(object sender, EventArgs e)
{

    List<Fruit> FruitList = new List<Fruit>();

    // create an apple and orange Fruit struct and add to List<Fruit>.
    Fruit apple = new Fruit();
    apple.FruitName = "Apple";
    apple.Price = "3.99";
    FruitList.Add(apple);

    Fruit orange = new Fruit();
    orange.FruitName = "Orange";
    orange.Price = "5.99";
    FruitList.Add(orange);


    // now bind the List to the repeater:
    repFruit.DataSource = FruitList;
    repFruit.DataBind();

}

我有一个简单的结构来模拟 Fruit,我们有两个属性,即 FruitName 和 Price。我首先创建一个类型为“FruitList”的空通用列表。

然后我使用该结构创建了两个水果(苹果和橙子)。然后将这些水果添加到列表中。

最后,我将泛型列表绑定(bind)到转发器的 DataSource 属性...

标记如下所示:

<asp:repeater ID="repFruit" runat="server">
<ItemTemplate>
    Name: <%# Eval("FruitName") %><br />
    Price: <%# Eval("Price") %><br />
    <hr />
</ItemTemplate>

我希望在屏幕上看到水果名称和价格,中间用横线分隔。

目前我收到与实际绑定(bind)相关的错误...

**Exception Details: System.Web.HttpException: DataBinding: '_Default+Fruit' does not contain a property with the name 'FruitName'.**

我什至不确定这是否可行?有什么想法吗?

谢谢

最佳答案

您需要将公共(public)字段更改为公共(public)属性。

改变这个:public string FruitName;

收件人:

public string FruitName { get; set; }

否则,您可以将 fruitName 设为私有(private)并为其包含一个公共(public)属性。

private string fruitName;

public string FruitName { get { return fruitName; } set { fruitName = value; } }

Here is a link with someone who has had the same issue as you.

关于c# - 将 struct 类型的通用列表绑定(bind)到 Repeater,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3525660/

相关文章:

Python:将几个嵌套列表组合成一个字典

c# - StreamReader 与 MemoryStream.ToArray

c# - 匹配系统的表设计

c# - 调用 ToList() 后的 Entity Framework 更改跟踪

c# - 在 ASP.Net 应用程序中添加数据集问题

asp.net - 一个网站多个​​应用程序池

Java链表-NullPointerException

c# - 将 YamlDotNet 插件中的 YamlStream 保存到文本文件

jquery - 在页面加载时选择下拉列表中选择选项

java - 以最小成本(时间和空间)的图形表示