2009-04-20 14 views
1

我有一個GridView通過LINQ表達式填充。
事情是這樣的:如果我用匿名對象填充GridView,我如何獲得它們的屬性?

GridView1.DataSource = from c in customers, o in c.Orders, 
    total = o.Total where total >= 2000 select new {id = c.CustomerID, 
    order = o.OrderID, total = total}; 

,並在其RowCreated方法我試圖得到一個屬性,例如ID,但它沒有一個已知類型:

object element = e.Row.DataItem; 
int id = element.id; // It's bad!!!!!! 

我怎麼能做?
謝謝!

回答

4

命名您的類型!

public class GridType 
{ 
    public int Id {get; set:} . . etc 
} 

然後在LINQ,

. . . select new GridType {...etc} 

然後在RowCreated方法,施放的DataItem到GridType,你可以CCESS它的屬性。

否則,您會尋找C#沒有做的鴨子打字。

+0

這是正確的滾動方式。 – 2009-04-20 15:27:07

2

您需要使用反射。

Type t = element.GetType(); 
int id = 0; 

foreach (PropertyInfo p in t.GetProperties()) 
{ 
    // Not very nice but finds an integer property called "id" 
    if (p.PropertyType == typeof(int) && p.Name == "id") 
    { 
     id = (int)p.GetValue(element, null); 
    } 
} 

使用LINQ:

Type t = element.GetType(); 
int id = 0; 
var pt = new List<PropertyInfo>(); 
pt.AddRange(t.GetProperties()); 
id = (int)pt.Where(p => p.PropertyType == typeof(int) && p.Name == "id").First().GetValue(element, null); 

不知道它會讀取任何好轉,雖然,特別是Type.GetProperties返回一個必須轉換到一個列表,以獲得在LINQ的方法的數組。

1

如果您想使用匿名對象,這是您必須付出的代價:當您離開聲明對象的範圍時,您將丟失強類型。我建議明確聲明你的類型,除非你想玩DataBinder.Eval ...

相關問題