【问题标题】:LINQ-to-XML to DataGridView: Cannot edit fields -- How to fix?LINQ-to-XML to DataGridView:无法编辑字段——如何修复?
【发布时间】:2010-04-28 22:29:20
【问题描述】:

我目前正在执行 LINQ-to-XML 并使用我的查询填充 DataGridView。我遇到的问题是,一旦加载到 DataGridView 中,这些值似乎是不可编辑的(只读)。这是我的代码:

var barcodes = (from src in xmldoc.Descendants("Container")
                where src.Descendants().Count() > 0
                select
                new
                {
                   Id = (string)src.Element("Id"),
                   Barcode = (string)src.Element("Barcode"),
                   Quantity = float.Parse((string)src.Element("Quantity").Attribute("value"))
                }).Distinct();

dataGridView1.DataSource = barcodes.ToList();

我在某处读到“当您使用匿名类型时,DataGridView 将处于只读模式。”但我找不到解释为什么或究竟该怎么做。

有什么想法吗?

编辑 -- 这是我想出的答案...

所以我添加了一个“容器”类(使用 Get 和 Set

    public class Container
    {
        public string Id { get; set; }
        public string Barcode { get; set; }
        public float Quantity { get; set; }
    }

    // For use with the Distinct() operator
    public class ContainerComparer : IEqualityComparer<Container>
    {
        public bool Equals(Container x, Container y)
        {
            return x.Id == y.Id;
        }

        public int GetHashCode(Container obj)
        {
            return obj.Id.GetHashCode();
        }
    }

并将 LINQ 语句更改为:

var barcodes = (from src in xmldoc.Descendants("Container")
            where src.Descendants().Count() > 0
            select
            new Container
            {
               Id = (string)src.Element("Id"),
               Barcode = (string)src.Element("Barcode"),
               Quantity = float.Parse((string)src.Element("Quantity").Attribute("value"))
            }).Distinct(new ContainerComparer());

就是这样!谢谢你的帮助,格伦!

【问题讨论】:

    标签: c# linq datagridview c#-3.0 linq-to-xml


    【解决方案1】:

    绑定匿名类型时数据网格视图处于只读模式的原因是匿名类型为ReadOnly。如果将视图绑定到具有只读属性的对象列表,您将获得相同的行为。

    我知道的唯一解决方案是为可编辑的数据创建一个容器。具有定义 get 和 set 的属性的类将为您提供您所追求的。

    【讨论】:

    • @Glenn:谢谢。这在我的脑海中是有道理的。虽然原谅我是一个 LINQ 新手,但我仍然试图了解引擎盖下发生的事情。令我困惑的是,匿名类型似乎仍会返回对每个值的引用,这样当 DataGridView 的字段中的值发生更改时,XDocument 中的 XML 数据也会同时更改。所以你是说如果我创建一个可以包含这些值的类,我就能得到我想要的东西?
    【解决方案2】:

    这可能是因为 C# 3 的限制 - 您不能使用匿名类型作为方法的返回类型。参见例如this

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-06
      • 1970-01-01
      • 2013-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-26
      相关资源
      最近更新 更多