Linq to Xml to Datagridview

Right, start losing your mind here. I have the following code:

var query = (from c in db.Descendants("Customer")
                             select c.Elements());
                dgvEditCusts.DataSource = query.ToList();

In this case, db refers to the call to XDocument.Load. How can I get data in a DataGridView?

Just thought I should mention: it returns a completely empty dgv.

Not that XML was too big, but here is an example:

<Root>
  <Customer>
    <CustomerNumber>1</CustomerNumber>
    <EntryDate>2010-04-13T21:59:46.4642+01:00</EntryDate>
    <Name>Customer Name</Name>
    <Address>Address</Address>
    <PostCode1>AB1</PostCode1>
    <PostCode2>2XY</PostCode2>
    <TelephoneNumber>0123456789</TelephoneNumber>
    <MobileNumber>0123456789</MobileNumber>
    <AlternativeNumber></AlternativeNumber>
    <EmailAddress>email@address.com</EmailAddress>
  </Customer>
</Root>
+3
source share
2 answers

Ah, never mind, I finally worked out the answer to my question. Here is the code for someone else who might have this problem:

var query = from c in db.Descendants("Customer")
                            select new
                            {
                                CustomerNumber = Convert.ToInt32((string)c.Element("CustomerNumber").Value),
                                Name = (string)c.Element("Name").Value,
                                Address = (string)c.Element("Address").Value,
                                Postcode = (string)c.Element("PostCode1").Value + " " + c.Element("PostCode2").Value
                            };
                dgvEditCusts.DataSource = query.ToList();
+1
source

When you call db.Descendants("Customer"), you return ONLY elements that have a name Customer. NOT these are children. See MSDN Docs .

, c.Elements(), , b/c, .

, , Customer.

+1

Source: https://habr.com/ru/post/1741007/


All Articles