2010-08-19 94 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定義的屬性。