通过LINQ绑定到XML文件后,无法编辑我的DataGridView[英] Can't edit my datagridview after binding to XML file via linq

本文是小编为大家收集整理的关于通过LINQ绑定到XML文件后,无法编辑我的DataGridView的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

链接到此处的2个类似示例,我无法真正链接到我的确切情况. similalr示例1

类似的示例2

这是填充我的datagridview的代码...

XElement xdoc = XElement.Load(@"C:\xmltest\test.xml");

            var lines = from item in xdoc.Descendants("line")
                        let fields = item.Elements("field")
                        select new
                        {
                            Name = (string)fields
                                .FirstOrDefault(n => (string)n.Attribute("name") == "Name"),
                            Description = (string)fields
                                .FirstOrDefault(n => (string)n.Attribute("name") == "Description"),
                            ExtraDetails = (string)fields
                                .FirstOrDefault(n => (string)n.Attribute("name") == "ExtraDetails"),

                        };


            dataGridView1.DataSource = lines.ToArray();

这可以正常工作,但是我无法在"导入"之后编辑DataGridView.我已经挑衅地设置了DataGridView设置以允许编辑等.问题似乎与数据宾灵语有关.

推荐答案

问题是您将结果投射到匿名类型.文档链接状态的第一行

匿名类型提供了一种方便的方法,可以将一组读取的属性封装到一个对象中,而无需明确定义类型.

希望您注意到只读单词.

如果要获取可编辑的数据,请使用读/写属性创建自己的类,并将查询结果投影到其中.

本文地址:https://www.itbaoku.cn/post/1557118.html

问题描述

Links to 2 similar examples on here which I can't really link to my exact case. Similalr example 1

Similar Example 2

Here is the code that populates my datagridview...

XElement xdoc = XElement.Load(@"C:\xmltest\test.xml");

            var lines = from item in xdoc.Descendants("line")
                        let fields = item.Elements("field")
                        select new
                        {
                            Name = (string)fields
                                .FirstOrDefault(n => (string)n.Attribute("name") == "Name"),
                            Description = (string)fields
                                .FirstOrDefault(n => (string)n.Attribute("name") == "Description"),
                            ExtraDetails = (string)fields
                                .FirstOrDefault(n => (string)n.Attribute("name") == "ExtraDetails"),

                        };


            dataGridView1.DataSource = lines.ToArray();

This works fine but I can't edit the datagridview after the 'import'. I have defiantly set the datagridview settings to allow editing etc. The problem seems to be related to the databind in some way.

推荐答案

The problem is that you are projecting the result to anonymous type. The very first line in the documentation link states

Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first.

Hope you noticed the read-only word.

If you want to get editable data, then create your own class with read/write properties and project the query result into it.