Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
438 views
in Technique[技术] by (71.8m points)

c# - unable to edit DataGridView populated with results of LINQ query

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;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, it is possible to bind to a list created from Linq-To-Xml. I tried to reproduce your problem. I did the following:

  1. Created an empty WindForm project (VS 2008 and .Net 3.5)
  2. Added a DataGridView to the Form.
  3. Wired the CellBeginEdit and CellEndEdit.
  4. Placed the following code in the Form's constructor

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;

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...