简体   繁体   中英

Binding a Generic List of type struct to a Repeater

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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