Populating a DataGridView from Xml Data

Posted Tue, Oct 20 2009 21:49 by Deborah Kurata

If you are using XML in a WinForms application you may find the need to display the XML data in a DataGridView.

Let's take this XML:

<states>
    <state name="California">
        <abbreviation>CA</abbreviation>
        <year>1850</year>
        <governor>Schwarzenegger</governor>
    </state>
    <state name="Wisconsin">
        <abbreviation>WI</abbreviation>
        <year>1848</year>
        <governor>Doyle</governor>
    </state>
</states>

Displaying XML in a DataGridView sounds easy, but if you just set the DataGridView DataSource to the XML data, you will get something like this:

image

Notice how it has lots of yuck in it: attribute details, node properties, and so on for every node in the XML. So how do you get something more like this:

image

The trick is to use anonymous types.

The code is provided here in VB and C# and then described in detail below.

NOTE: Be sure to set a reference to System.Core and System.Xml.Linq

In C#:

XElement statesXml = XElement.Parse("<states>" +
    "<state name='California'>" +
        "<abbreviation>CA</abbreviation>" +
        "<year>1850</year>" +
        "<governor>Schwarzenegger</governor>" +
    "</state>" +
    "<state name='Wisconsin'>" +
        "<abbreviation>WI</abbreviation>" +
        "<year>1848</year>" +
        "<governor>Doyle</governor>" +
    "</state>" +
   "</states>");

var query = from st in statesXml.Descendants("state")
            select new
            {
                Name = st.Attribute("name").Value,
                Abbrev = st.Element("abbreviation").Value,
                Year = st.Element("year").Value,
                Governor = st.Element("governor").Value
            };
DataGridView1.DataSource = query.ToList();

In VB:

Dim statesXml As XElement = _
    <states>
        <state name="California">
            <abbreviation>CA</abbreviation>
            <year>1850</year>
            <governor>Schwarzenegger</governor>
        </state>
        <state name="Wisconsin">
            <abbreviation>WI</abbreviation>
            <year>1848</year>
            <governor>Doyle</governor>
        </state>
    </states>

Dim query = From st In statesXml...<state> _
            Select New With { _
                  .Name = st.@name, _
                  .Abbrev = st.<abbreviation>.Value, _
                  .Year = st.<year>.Value, _
                  .Governor = st.<governor>.Value}
DataGridView1.DataSource = query.ToList

The first part of this code builds the XML. The C# code uses the XElement.Parse function to build the XML; VB uses XML literals. This part of the code is not necessary if you are reading the XML from another source, such as a file.

The second part of the code leverages Linq to XML to process the set of state XML elements. For each element, it uses the Select New syntax to create an anonymous type. The syntax defines an unnamed (anonymous) type with properties Name, Abbrev, Year, and Governor.

[To view an overview of anonymous types, start here.]

The last line converts the results of the query to a generic list and assigns it to the DataSource property of the DataGridView. Visual Studio uses the anonymous type property names as the text for the column titles and populates the rows with each state element.

Use this technique any time you have XML that you want to display in a DataGridView.

Enjoy!

Filed under: , , , , , , ,

Comments

# Anonymous Types: An Introduction

Tuesday, October 20, 2009 11:56 PM by Deborah's Developer MindScape

The last several posts have provided examples of using anonymous types. This post backs up a little and

# re: Populating a DataGridView from Xml Data

Sunday, October 25, 2009 5:20 PM by Ciro

Hi Deborah!

This post help me a lot.

Thank you!

# re: Populating a DataGridView from Xml Data

Monday, November 09, 2009 12:50 PM by Kathy Carson

Thanks so much for this post!!  

It really helped me with a quick prototype I had to whip up.

Kathy

# re: Populating a DataGridView from Xml Data

Tuesday, November 17, 2009 3:40 AM by Bunzo

Hi Deborah,

Exactly what I am looking for!

Merci beaucoup pour ce post

# re: Populating a DataGridView from Xml Data

Thursday, November 19, 2009 2:29 PM by Ilber

Hi Deborah,

I have this situation:

<Root>

   <Date Value="20091118">

     <MM Title="MyTitle" Note="MyTitle1" />

   </Date>

   <Date Value="20091119">

     <MM Title="Title2"Note="Title2" />

     <MM Title="Title3" Note="Titl3" />

   </Date>

   <Date Value="2009113">

     <MM Title="Tit4" Note="Tit4" />

   </Date>

 </Root>

When in child nodes i have only one child everything goes well when i read it, but if there are more then one note my query read only the first child.

This is my query:

Dim query = From st In inXLM...<Date> _

                           Select New With { _

                           .Data = st.Attribute("Value").Value, _

                           .MM = st.<MM>.@Title, _

                           .Note = st.<MM>.@Note}

Can you help me plese.

Thanks in advance,

Ilber

# re: Populating a DataGridView from Xml Data

Wednesday, June 09, 2010 11:54 AM by Erich

This is an excellent source! Almost exactly what I needed.

I have a question about building a datagridview when the xml source has many of the same child nodes. For example:

<library>

  <book>

      <review stars = "5">text here</review>

      <review stars = "4">more text</review>

      <review stars = "4">even more text</review>

  </book>

</library>

do you know of a method for displaying all reviews in a single row automatically without explicitly adding a new column for each? Maybe using a loop?

Thanks

# re: Populating a DataGridView from Xml Data

Saturday, July 24, 2010 1:49 AM by Lentucky

Exactly what I looking for!

A good example of LinQ to XML with the DataGridView control.

Works also with an existing XML document, using the XDocument instead a XElement with the XDocument.Load({PATH}.xml) method.

Thank you very much from Paraguay!

# re: Populating a DataGridView from Xml Data

Thursday, October 07, 2010 11:05 AM by Blackwurst

Hi!

Thanks! But the cells are now uneditable.

How can I make the cells editable?

# re: Populating a DataGridView from Xml Data

Friday, October 08, 2010 1:01 AM by Deborah Kurata

You must be using C#. :-)

In VB, anonymous types are mutable. In C#, anonymous types are immutable and cannot be changed.

To make this grid editable when using C#, you need to define a named type instead of an anonymous type. So create a State class with Name, Abbrev, Year, and Governor properties. Then create an instance of this class in my code instead of an anonymous type.

Hope this helps!

# re: Populating a DataGridView from Xml Data

Wednesday, October 20, 2010 2:41 PM by Al

Hi,

Excellent post, very useful. I've been trawling around for a while looking for a neat way of displaying xml in a datagridview and this tops them all. In particular, the control of column header names is really cool.

Thanks,

Al

# re: Populating a DataGridView from Xml Data

Thursday, February 10, 2011 9:25 AM by DaveH

Thank you.

# re: Populating a DataGridView from Xml Data

Wednesday, May 04, 2011 12:51 PM by Jeff

Ok, fine if you only want to just display the data from xml and not edit it. seems using this method breaks the binding references such that the items are no longer editable.

# re: Populating a DataGridView from Xml Data

Wednesday, May 04, 2011 6:24 PM by Deborah Kurata

Hi Jeff -

See my reply to Blackwurst.

Hope this helps.

# re: Populating a DataGridView from Xml Data

Saturday, July 16, 2011 1:29 AM by Santanu Dutta

Hi Deborah,

Thanks a lot for this post. This is just unputdownable!

Although my requirement is something more. As I have to display an image (which residing in XML, base64 encoded) as an icon and all corresponding data of that image as text, in a DataGridView. Do you have any idea?

Thanks in advance.

Santanu Dutta

# re: Populating a DataGridView from Xml Data

Thursday, January 05, 2012 5:17 AM by Gaurav Pant

Very informative post. It's really helpful for me and helped me lot to complete my task. Thanks for sharing with us. I had found another nice post over the internet which was also explained very well about Populate Grid Control From XML Document Easily, for more details of this post check out this link...

mindstick.com/.../6c3ccf8c-6656-4a48-bfb7-e0221569de67

Thanks Everyone!!

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above: