0

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

4

1 回答 1

0

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

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

我遇到的缺点是,例如要进行排序,您将需要实现自己的排序方法。

于 2013-02-20T13:10:49.063 回答