如何将linq查询用作TreeView或GridView的数据源

时间:2012-11-07 15:09:52

标签: c#-4.0 treeview linq-to-xml xmldatasource

我试图找到一种方法来使用我的linq查询的结果作为C#中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创建数据源的代码部分无法正常工作。可以通过保存文件然后调用数据源文件来使其工作,但我想从内存中执行此操作。

1 个答案:

答案 0 :(得分:0)

您可以直接将linq查询结果用作数据源。

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

我遇到的缺点是,为了使例如排序工作,你需要实现自己的排序方法。