Linq to Xml to Datagridview

狂风中的少年 提交于 2020-01-13 18:57:38

问题


Right, starting to go crazy here. I have the following code:

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

In this, db relates to an XDocument.Load call. How can I get the data into the DataGridView?

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

Not that the XML should matter too much, but here's 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>

回答1:


When you call db.Descendants("Customer") you are returning ONLY the elements that have the name Customer in it. NOT it's children. See MSDN Docs.

So when you call c.Elements() it is trying to get the Customer's child elements which don't exist b/c they were filtered out.

I think it might work if you drop the Customer filtering.




回答2:


Ah, never mind, I've worked out the answer to my own question eventually. Here's the code for anyone else that may 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();


来源:https://stackoverflow.com/questions/2633745/linq-to-xml-to-datagridview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!