问题描述
当我使用 linq-to-xml 查询的结果填充 datagridview 时,我无法编辑 datagridview.我试过将 datagridview 的 readonly 属性设置为 false ,但这没有帮助.我还为 cellBeginEdit 添加了一个事件处理程序并在那里放置了一个断点,但它没有被命中.知道我做错了什么,或者这是不可能的吗?
When i use the results of a linq-to-xml query to populate a datagridview, i cannot edit the datagridview. i've tried setting the datagridview's readonly property to false and that doesn't help. I also added an event handler for cellBeginEdit and put a breakpoint there, but it doesn't get hit. Any idea what i'm doing wrong, or if this isn't possible?
public class MergeEntry
{
public string author { get; set; }
public string message { get; set; }
}
...
var query = from entry in xmlDoc.Descendants("entry")
select new MergeEntry
{
author = entry.Element("author").Value,
message = entry.Element("msg").Value,
}
var queryAsList = query.ToList();
myBindingSource.DataSource = queryAsList;
myDataGridView.DataSource = myBindingSource;
推荐答案
是的,可以绑定到从 Linq-To-Xml 创建的列表.我试图重现你的问题.我做了以下事情:
Yes, it is possible to bind to a list created from Linq-To-Xml. I tried to reproduce your problem. I did the following:
- 创建了一个空的 WindForm 项目(VS 2008 和 .Net 3.5)
- 在表单中添加了一个 DataGridView.
- 连接 CellBeginEdit 和 CellEndEdit.
- 将以下代码放入表单的构造函数中
string testXML =
@"<p><entry>
<author>TestAuthor1</author>
<msg>TestMsg1</msg>
</entry></p>
";
XElement xmlDoc = XElement.Parse(testXML);
var query = from entry in xmlDoc.Descendants("entry")
select new MergeEntry
{
author = entry.Element("author").Value,
message = entry.Element("msg").Value,
}; //You were missing the ";" in your post, I am assuming that was a typo.
//I first binded to a List, that worked fine. I then changed it to use a BindingList
//to support two-way binding.
var queryAsList = new BindingList<MergeEntry>(query.ToList());
bindingSource1.DataSource = queryAsList;
dataGridView1.DataSource = bindingSource1;
运行 WinForm 应用程序时,显示了一个可编辑的网格,并且 CellBeginEdit 和 CellEndEdit 事件在它们应该触发的时候被触发.希望尝试使用上述步骤进行重现将帮助您找到您面临的问题.
When running the WinForm app, an editable grid was displayed and the CellBeginEdit and CellEndEdit events were fired when they should have been. Hopefully trying to reproduce using the above steps will help you locate the issue you are facing.
这篇关于无法编辑填充有 LINQ 查询结果的 DataGridView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!