Getting values from DataGridView back to XDocument (using LINQ-to-XML)
Posted
by Pretzel
on Stack Overflow
See other posts from Stack Overflow
or by Pretzel
Published on 2010-04-29T15:07:51Z
Indexed on
2010/04/29
16:17 UTC
Read the original article
Hit count: 452
Learning LINQ has been a lot of fun so far, but despite reading a couple books and a bunch of online resources on the topic, I still feel like a total n00b. Recently, I just learned that if my query returns an Anonymous type, the DataGridView I'm populating will be ReadOnly (because, apparently Anonymous types are ReadOnly.)
Right now, I'm trying to figure out the easiest way to:
- Get a subset of data from an XML file into a DataGridView,
- Allow the user to edit said data,
- Stick the changed data back into the XML file.
So far I have Steps 1 and 2 figured out:
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();
}
}
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());
dataGridView1.DataSource = barcodes.ToList();
This works great at getting the data I want from the XML into the DataGridView so that the user has a way to manipulate the values.
Upon doing a Step-thru trace of my code, I'm finding that the changes to the values made in DataGridView are not bound to the XDocument object and as such, do not propagate back.
How do we take care of Step 3? (getting the data back to the XML) Is it possible to Bind the XML directly to the DataGridView? Or do I have to write another LINQ statement to get the data from the DGV back to the XDocument?
Suggstions?
© Stack Overflow or respective owner