Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 488
Dalbir Singh Avatar asked Aug 19 '10 19:08

Dalbir Singh


2 Answers

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.

like image 152
JonH Avatar answered Nov 19 '22 13:11

JonH


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

like image 39
epitka Avatar answered Nov 19 '22 13:11

epitka