views:

74

answers:

2

Hi All

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  A: 

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

epitka
+1  A: 

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.

JonH
It worked! God I feel soo stupid now, makes a lot of sense, thank you very much!! :)
Dal