2010-08-19 42 views
7

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

我已经建立了下面一个简单的例子:

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

} 

我有一个简单的结构,以水果模型,我们有这两种性能FruitName和价格。我首先创建一个类型为'FruitList'的空泛型列表。

然后我使用struct(apple和orange)创建两个水果。这些水果然后被添加到列表中。

最后,我绑定泛型列表到中继器的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'.** 

我什至不知道这是否可以正常工作?有任何想法吗?

谢谢

+1

随机音符,ListView控件类是大量取代了能力方面的中继器。 – 2010-08-19 20:01:50

+0

@Chris Marisic感谢您的提示,我现在阅读有关ListView,看起来非常好:http://weblogs.asp.net/scottgu/archive/2007/08/10/the-asp-listview-control- part-1-building-a-product-listing-page-with-clean-css-ui.aspx – Dal 2010-08-19 20:34:14

回答

9

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

更改此: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.

+0

它工作!上帝,我现在觉得自己很愚蠢,很有道理,非常感谢你! :) – Dal 2010-08-19 20:05:46

1

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