【问题标题】:Binding a Generic List of type struct to a Repeater将结构类型的通用列表绑定到中继器
【发布时间】:2011-04-01 08:07:54
【问题描述】:

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

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

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”类型的空通用列表。

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

最后,我将通用列表绑定到转发器的 DataSource 属性...

标记如下所示:

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

我希望看到打印在屏幕上的水果名称和价格,由水平线分隔。

目前我收到与实际绑定有关的错误...

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

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

谢谢

【问题讨论】:

标签: c# asp.net list repeater generics


【解决方案1】:

您需要将您的公共字段更改为公共属性。

改变这个:public string FruitName;

收件人:

public string FruitName { get; set; }

否则,您可以将 fruitName 设为私有并为其包含公共属性。

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.

【讨论】:

  • 成功了!上帝,我现在觉得很愚蠢,很有道理,非常感谢!! :)
【解决方案2】:

错误告诉你你需要知道的一切。您有公共字段,而不是为 FruitName 和 Price 定义的属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    • 1970-01-01
    • 2016-08-19
    • 1970-01-01
    • 2017-11-03
    • 2018-02-10
    相关资源
    最近更新 更多