Binding a Generic List of type struct to a Repeater

六眼飞鱼酱① 提交于 2020-01-14 08:00:32

问题


I've had a bit of a problem trying to bind a generic list to a repeater. The type used in the generic list is actually a struct.

I've built a basic example below:

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();

}

I have a simple struct to model Fruit, we have two properties which are FruitName and Price. I start by creating an empty generic list of type 'FruitList'.

I then create two fruits using the struct (apple and orange). These fruits are then added to the list.

Finally, I bind the generic list to the DataSource property of the repeater...

The markup looks like this:

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

I expect to see the fruit name and price printed on the screen, separated by a horizontal rule.

At the moment I am getting an error relating to actual binding...

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

I'm not even sure if this can work? Any Ideas?

Thanks


回答1:


You need to change your public field into a public property.

Change this: public string FruitName;

To:

public string FruitName { get; set; }

Otherwise you could make fruitName private and include a public property for it.

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:


Error tells you everything you need to know. You have public fields not properties defined for FruitName and Price.



来源:https://stackoverflow.com/questions/3525660/binding-a-generic-list-of-type-struct-to-a-repeater

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!