2012-11-07 25 views
0

我試圖找到一種方法來使用我的linq查詢的結果作爲C#中TreeView和GridView的數據源,而不必先保存文件在服務器中。已經嘗試了各種選項,但都要求將文檔先保存爲文件。有人可以幫我嗎?下面的代碼給出:我如何使用linq查詢作爲TreeView或GridView的數據源

XDocument products = new XDocument(
     new XDeclaration("1.0", "utf-8", ""), 
      new XElement("products", 
       new XElement("product", new XAttribute("id", "p1"), 
         new XElement("name", "Alpha"), 
         new XElement("Address", "200 WATERLOO DRIVE"), 
         new XElement("price", 
          new XElement("currency", "Rs.")), 
         new XElement("stock", "19"), 
         new XElement("country", "USA", 
          new XElement("state", "California"))), 
       new XElement("product", new XAttribute("id", "p2"), 
         new XElement("name", "Beta"), 
         new XElement("Address", "500 MOUNTBATTEN AVENUE"), 
         new XElement("price", 
          new XElement("currency", "Rs.")), 
         new XElement("stock", "25"), 
         new XElement("country", "USA", 
          new XElement("state", "Florida"))))); 
//create a linq query 
var newxml = from f1 in products.Elements("product") 
         where (string)f1.Element("country").Element("state") != "Florida" 
         select f1; 

//Create an xml document in memory using the linq query 
XDocument xdoc = new XDocument(
     new XDeclaration("1.0", "utf-8", ""), 
     new XElement("products")); 
xdoc.Element("products").Add(newxml); 

//create a datasource for TreeView or GridView using the xml document in memory. 
XmlDataSource xmlds = new XmlDataSource(); 
xmlds.DataFile=xdoc; 
TreeView1.DataSource = xmlds; 
TreeView1.DataBind(); 
GridView1.DataSource = xmlds; 
GridView1.DataBind(); 

代碼的一部分,從創建XDOC不正常的數據源。可以通過保存文件然後調用數據源的文件來工作,但我想從內存中執行此操作。

回答

0

您可以直接使用linq查詢結果作爲數據源。

gridview1.datasource = newxml; gridview1.databind();

我遇到的缺點是,例如排序工作,你將需要實現自己的排序方法。