Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

October 20, 2009

Populating a DataGridView from Xml Data

Filed under: C#,Data Binding,LINQ,VB.NET,WinForms,XML @ 11:49 pm

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!

14 Comments

  1.   Jeff — May 4, 2011 @ 12:51 pm    Reply

    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.

  2.   DeborahK — May 4, 2011 @ 6:24 pm    Reply

    Hi Jeff –

    See my reply to Blackwurst.

    Hope this helps.

  3.   Santanu Dutta — July 16, 2011 @ 1:29 am    Reply

    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

  4.   Gaurav Pant — January 5, 2012 @ 5:17 am    Reply

    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…

    http://mindstick.com/Articles/6c3ccf8c-6656-4a48-bfb7-e0221569de67/?Populate%20Grid%20Control%20From%20XML%20Document%20Easily

    Thanks Everyone!!

RSS feed for comments on this post. TrackBack URI

Leave a comment

© 2019 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs