2011-10-15 183 views
2

我在排序gridview時遇到錯誤。我的數據源是一個變種的結果,這我得到直通LINQ查詢無法將類型爲「System.Collections.Generic.List」的對象轉換爲鍵入'System.Data.DataSet'

protected void Page_Load(object sender, EventArgs e) 
{ 
    dt1 = obj1.Table1data().Tables[0]; 
    dt2 = obj1.Table2data().Tables[0]; 
    dt3 = obj1.Table3data().Tables[0]; 

    var results = (
     from table1 in dt1.AsEnumerable() 
     join table2 in dt2.AsEnumerable() on (int)table1["id"] equals (int)table2["id"] 
     join table3 in dt3.AsEnumerable() on (int)table1["id"] equals (int)table3["id"] 

     select new 
     { 
      id = (int)table1["id"], 
      S1= (int)table1["S1"], 
      P1= (double)table1["P1"], 
      P2= (int)table2["P2"], 
      P3= (double)table2["P3"], 
      P4 = (int)table3["P4"], 
      P5= (double)table3["P5"], 

     }).ToList(); 

    Session["ds"] = results; 
    GridView1.DataSource = results; 
    GridView1.DataBind(); 
} 

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e) 
{ 
    DataSet dataSet = (DataSet)Session["ds"]; 
    DataTable dataTable = dataSet.Tables[0]; 

    if (dataTable != null) 
    { 
     DataView dataView = new DataView(dataTable); 
     dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection); 

     GridView1.DataSource = dataView; 
     GridView1.DataBind(); 
    } 
} 

// here in the GridView1_sorting at DataSet dataSet = (DataSet)Session["ds"], I am getting an error 

錯誤:

Unable to cast object of type System.Collections.Generic.List`1[<>f__AnonymousType5`8[System.Int32,System.String,System.Int32,System.Double,System.Int32,System.Double,System.Int32,System.Double]]' to type 'System.Data.DataSet' 

2)另外一個問題,什麼是VAR結果的數據類型。 由於 太陽

回答

3

Session["ds"]保持var results,和resultsList<'A>,其中'A是由編譯器產生的匿名類型。你不能將它投射到DataSet。如果你想把它放到會話中並在稍後檢索它,請聲明一個合適的類,然後可以輕鬆地將列表放入Session中或放入Session中。

我的意思是,你的查詢是建立一個匿名類型,因爲select聲明

select new 
{ 

這通常是罰款,但你試圖通過將使用這個結果超越眼前的局部範圍它進入會議。你需要建立一個適當的類來保存這些數據。給它正確的屬性。

public class MyData 
{ 
     // give it the appropriate properties you need 
     public int ID { get; set; } 
     public int S1 { get; set; } 
     public double P1 { get; set; } 
     public int P2 { get; set; } 
     public double P3 { get; set; } 
     public int P4 { get; set; } 
     public double P5 { get; set; } 
     // by the way... you should really come up with better names 
     // for these properties! 
} 

然後進行查詢

select new MyData 
{ 

當你調用ToList()和結果,你將有List<MyData>。所以當你從會話中檢索這個時候,這就是你想要的。

var list = (List<MyData>)Session["ds"]; 
+0

您好,感謝您的答覆。但你如何建議我做分類。我應該在列表上實施這種排序嗎?我的意思是保護無效GridView1_Sorting(對象發件人,GridViewSortEventArgs e) { var list =(List )Session [「ds」]; ... ..... }這些屬性只是隨機名我有這個職位。 – user575219

+0

您可以檢查排序表達式,然後可以使用Linq'OrderBy'方法構建。例如,'var query = list.AsEnumerable(); (e.SortExpression ==「ID」){query = query.OrderBy(item => item.ID); }'搜索用對象列表排序gridviews以獲得更多想法。 –

相關問題