Working with XML in Windows Forms Application in C# - Part 1
Introduction
In this series of articles, we will be looking at how to use XML files as a storage medium when Programming Windows Forms. In this first part, we will look how we can connect to an XML file and retrieve all the data that is in it, as well as filter the data to retrieve a sub-set of the data based on criteria we specify.
This article series makes use of LINQ to XML, which is built into the .NET Framework 3.5, so if you are using .NET 2.0, then steps in this article may differ for you, as a LINQ Preview can be downloaded directly from Microsoft.
I just signed up at Server Intellect and couldn't be more pleased with my Windows Server! Check it out and see for yourself.
What we will learn in this article:
- How to connect to and retrieve data from an XML file using Windows Forms;
- How to filter XML data to retrieve a sub-set of data from an external XML file.
Getting Started
Before we do anything, we need to start our project in Visual Studio and then create our XML file structure. Once you have VS opened, click File > New > Project. Then Choose Visual C#, Windows, Windows Forms Application. Give it a name.
Once we click Ok, we should be greeted with a blank Windows Form in design view. To the right, we want to right-click on our project in Solution Explorer, and choose Add > New Item.. XML File. Name it VideoGames.xml
Now we should be presented with an empty XML file. For this example, we will create a structure which contains video game titles for different platforms. We will include the game title and the format.
Server Intellect offers Windows Hosting Dedicated Servers at affordable prices. I'm very pleased!
<VGames>
<Platform>XBOX360</Platform>
<Game>
<Platform>PS3</Platform>
<Game>
<Platform>PC</Platform>
<Game>
<Platform>Wii</Platform>
<Game>
<Platform>XBOX360</Platform>
<Game>
<Platform>Wii</Platform>
<Game>
<Platform>PS3</Platform>
Save the changes. Now that we have our XML file ready, we can begin to design the form. The form should need to be able to display the whole contents of the XML file on demand. This means that we must allow for scrolling, to ensure that all data can fit. The easiest way to do this is to use a RichTextBox control. Let's go ahead and drag one of these onto the form. Go over to the Toolbox and locate the RichTextBox control, in Common Controls.
Once we click and drag onto the Form, we can resize as needed. Notice the blue marker guides that appear when you move it to the edge of the form. These guides keep you within a margin of the form and make it easy to align controls. The guides also appear around other controls when moving, which allows us to position our controls uniformly.

Try Server Intellect for Windows Server Hosting. Quality and Quantity!
The RichTextBox will automatically scroll when text overflows its boundaries. This makes it a useful control in this case, or any case in which you're loading text and don't know exactly how long it may be. Once the RichTextBox is placed, change it's (Name) in the Properties Window to txtResults.
Next, we will also add two buttons to the form, as well as a Label and a Combo Box. Drag these controls onto the form the same way you did the Rich Text Box, and then change the following properties of each control:
Button 1
(Name): butGetAll
Text: Get All Data
Combo Box
(Name): cmbPlatform
Button 2
(Name): butFilter
Text: Filter
Label
Text: Filter By Platform:
You can also change the Text attribute of the Form itself if you so wish, which is Form1 by default.

Once we have designed our form and named the controls, we can move onto the back-end and start our coding. To get to the code-behind, double click on one of the buttons in design view. This will open up the code-behind. Go back to the form design view and double click on the other button. This will create the event handlers for both of our buttons.
Server Intellect assists companies of all sizes with their hosting needs by offering fully configured server solutions coupled with proactive server management services. Server Intellect specializes in providing complete internet-ready server solutions backed by their expert 24/365 proactive support team.
NOTE: Before we proceed, it is important to note that while in development, VS is unable to load the XML file from the project root directory. This is because when we run the application from with VS, the application root directory is /bin/debug/
We can temporarily copy the XML file to this directory while we test the application within VS.
We will start by coding the GetAll button, but before we do even that, we will add a reference to the System.Xml.Linq namespace at the top of our code. We are going to use LINQ to open the XML file and select all the data and finally assign it to the RichTextBox control we added to the form earlier.
{
var games = from game in xmlDoc.Descendants("Game")
{
Platform = game.Element("Platform").Value,
txtResults.Text = "";
foreach (var game in games)
{
txtResults.Text = txtResults.Text + "Platform: " + game.Platform + "\n\n";
if (txtResults.Text == "")
You'll notice that the LINQ statement is similar to a SQL statement to get the XML data. Once we have the data, we then loop through it and add each element into our RichTextBox. The \n escape charater is to output a new line in the textbox. The output will look like this:

All data existing in the XML file is returned at present, but we did add a filter option. We will use this to filter the XML data to only return matches for a certain Platform. In order to accomplish this, we are going to need to first populate the combo box with the Platforms from the XML file.
For this method we are about to create, we will need to reference the System.Xml namespace.
We will create a new method to populate the combo box, and then call it on form load. The method will load the XML file and select the Game node, and checking each element, we will add each unique Platform value to the combo box. This means that we will have all values in the XML file, but no duplicate platforms in our combo box to choose from.
If you're looking for a really good web host, try Server Intellect - we found the setup procedure and control panel, very easy to adapt to and their IT team is awesome!
{
private void populateCombo()
{
XmlDocument doc = new XmlDocument();
doc.Load("VideoGames.xml");
XmlNodeList nodeList = doc.SelectNodes("VGames/Game");
foreach(XmlNode node in nodeList)

Finally, all that is left for us to do is to code the Filter button, which will work in much the same way as the GetAll button, except we'll be limiting the returned data to what matches the combo box value. We do this by specifying a SQL-like where clause in our LINQ select statement.
{
var games = from game in xmlDoc.Descendants("Game")
select new
{
Platform = game.Element("Platform").Value,
txtResults.Text = "";
foreach (var game in games)
{
txtResults.Text = txtResults.Text + "Platform: " + game.Platform + "\n\n";
if (txtResults.Text == "")
If you're ever in the market for some great Windows web hosting, try Server Intellect. We have been very pleased with their services and most importantly, technical support.
We match the Platform element to the selected item in the combo box, and if they match, we add it to the Rich Text Box.

What we have Learned
We have learned how to create a Windows Forms Application that can retrieve and filter XML data from an external file.
Attachments





Leave a Comment
#1 mohasin
Posted By: mohasin | 10.03.2008 at 3:09 AM
i like your site.
#2 Baudin
Posted By: Baudin | 11.17.2008 at 11:01 AM
Great tutorial for the beginning programmer. If I might give a tip, try and seperate the real XML stuff from teh winforms logic and either comment on the latter in a different document or assume the reader understands that part already :)
keep up the great tutorials!
#3 narender
Posted By: narender | 11.25.2008 at 6:44 AM
thanks a lot david, this tutorial is provide me great help to find unique values from elements.
#4 vijayvardhan
Posted By: vijayvardhan | 12.01.2008 at 10:15 AM
very nice site
#5 Gadekatte P.B.
Posted By: Gadekatte P.B. | 2.09.2009 at 7:43 AM
Hi,
This is really good for beginners.and it gives lot of concepts over xml and combo.
thanks and regards
Gadekatte P.B.
#6 Dulwan Baddewithana
Posted By: Dulwan Baddewithana | 4.08.2009 at 9:43 PM
Nothing to say.It's just fabulous.
#7 Jay
Posted By: Jay | 4.27.2009 at 2:53 PM
Hi there I been looking for something like this for a long time, how would I change the filter button to enable me to type into the box then click display ? many thanks
jay
#8 Steffen
Posted By: Steffen | 6.11.2009 at 8:37 AM
Dat Tut ist sauber geschrieben und sehr .. super Hilfreich. Danke dafuer...
Gruss Steffen
#9 ryan24
Posted By: ryan24 | 8.20.2009 at 8:49 AM
great tuto so clear
thans
#10 Tiffany Rings
Posted By: Tiffany Rings | 10.23.2009 at 7:37 AM
i like
#11 Praseetha
Posted By: Praseetha | 11.10.2009 at 9:27 AM
THank you so much. this tutorial was indeed a godsend.
#12 http://www.sitiblackjack.com/
Posted By: http://www.sitiblackjack.com/ | 11.27.2009 at 10:33 PM
XML is a extensible markup language and used to transport and store data.XML and HTML are two different things because XML is used to store data while HTML is used to display data.Maybe it is a little hard to understand, but XML does not DO anything. XML was created to structure, store, and transport information.Example which you have given above I think it is good for beginner who just started to learn XML.
Example of XML is
<?xml version="1.0"encoding="ISO-8859-1"?>//
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
#13 anindya chatterjee
Posted By: anindya chatterjee | 12.05.2009 at 1:17 PM
it is really helpful for a fresher like me.I was interested to know that .
Thanks for it.
#14 anindya chatterjee
Posted By: anindya chatterjee | 12.05.2009 at 1:27 PM
good article for a fresher like me.thanks
#15 mobile application development
Posted By: mobile application development | 12.06.2009 at 12:57 PM
Thanks for the really useful article. Working with XML isn't an easy thing and it is always hard for me to do something when I am facing it. Your explanation is very detailed so it will be better then a book for me. Thanks one more time for publishing it here and I will be waiting for more interesting ones from you in the nearest future.
#16 JordancoD
Posted By: JordancoD | 12.10.2009 at 3:17 AM
Nice Site
#17 Train Horns
Posted By: Train Horns | 12.17.2009 at 4:40 AM
I didn't know it was possible to use XML as a storage for windows forms. This seems to be an easy way out, must try this code. Thanks.
#18 Second Chance Checking
Posted By: Second Chance Checking | 12.22.2009 at 2:01 AM
I really appreciate you sharing this tutorial with us. I am benefiting from it. Thanks.
#19 Horse Saddles
Posted By: Horse Saddles | 12.23.2009 at 12:52 AM
Thanks for sharing the guide for working with xml in window application forms
#20 handbags shop
Posted By: handbags shop | 12.26.2009 at 12:29 AM
i like
#21 handbags shop
Posted By: handbags shop | 12.26.2009 at 12:29 AM
i like
#22 reviewsgoldmine
Posted By: reviewsgoldmine | 1.09.2010 at 2:17 AM
Interesting article,i think this is great tutorial for the beginning programmer. I will make sure my friend Ricky reads this given that it is his field. Thanks
#23 cash advance loans online
Posted By: cash advance loans online | 1.13.2010 at 8:06 AM
Thanks a lot for the informative post indeed. I have to admit that some information was a little bit difficult for me to understand... Anyway I think that it is really useful because I have known many new things about windows form applications. Thanks a lot one more time for sharing this useful information. I will definitely bookmark your website.
#24 dhanil manuel
Posted By: dhanil manuel | 1.19.2010 at 3:17 AM
great!...really informative...
#25 New Homes Henrico
Posted By: New Homes Henrico | 2.09.2010 at 6:35 AM
This will definitely create some interest in the minds of many working professionals. Thanks!
#26 coach handbag outlet
Posted By: coach handbag outlet | 2.28.2010 at 8:24 PM
The variety of coach handbags are so many that it almost becomes difficult to choose the right one.
#27 games funny
Posted By: games funny | 3.07.2010 at 3:41 AM
I really loved this interesting article. Please keep them coming. Cheers..
#28 Rupesh
Posted By: Rupesh | 3.10.2010 at 11:48 AM
This is a great way to make understand..
Really its useful...
Thanks...
#29 1Z0-053 dumps
Posted By: 1Z0-053 dumps | 3.19.2010 at 5:41 AM
For all I know this could be a really old entry, since there are no date marker on the article. In that case I apologize.
#30 Richard
Posted By: Richard | 3.31.2010 at 6:02 PM
I couldn't compile it. Visual studio gave me errors:
Error 1 The type or namespace name 'XmlDocument' could not be found (are you missing a using directive or an assembly reference?)
same for 'XmlNodeList' and 'XmlNode'.
Help please?
private void populateCombo() {
cmbPlatform.Items.Clear();
XmlDocument doc = new XmlDocument();
doc.Load("VideoGames.xml");
XmlNodeList nodeList = doc.SelectNodes("VGames/Game");
foreach (XmlNode node in nodeList)
if (!cmbPlatform.Items.Contains(node.SelectSingleNode("Platform").InnerText))
cmbPlatform.Items.Add(node.SelectSingleNode("Platform").InnerText);
}
#31 discount coach handbag
Posted By: discount coach handbag | 4.09.2010 at 9:30 PM
Welcome to our network station and you will get great surprise!
www.discountcoachhandbag.com coach handbags,
www.discountcoachhandbag.com/.../coach-c-2.html coach handbag outlet,
discount christian louboutin
www.louboutindiscounting.com
www.mbttrainersshoes.com
MBT shoes sale
#32 annuity quotes
Posted By: annuity quotes | 4.15.2010 at 8:28 AM
I found you. Thanks for this tutorial. You really solve my problem.
#33 horse fence
Posted By: horse fence | 5.10.2010 at 11:13 PM
I have to admit that some information was a little bit difficult for me to understand... Anyway I think that it is really useful because I have known many new things about windows form applications. Thanks a lot one more time for sharing this useful information. I will definitely bookmark your website.
#34 Premium Cigar
Posted By: Premium Cigar | 5.13.2010 at 4:05 PM
Yooo! This is awesome information and im not even a computer guy. LEt me knoe if post any other information about doing things for the PS3
#35 T M Lewin
Posted By: T M Lewin | 5.18.2010 at 3:38 AM
i've been using xml in product feeds and once you get your head around it, its rather easy
#36 testking E20-501
Posted By: testking E20-501 | 5.18.2010 at 8:27 AM
I like your blog very much.
#37 testking HP2-E27
Posted By: testking HP2-E27 | 5.18.2010 at 8:27 AM
Your blog is great.
#38 testking 1z0-048
Posted By: testking 1z0-048 | 5.18.2010 at 8:27 AM
Thanks for sharing. Your blog is great.
#39 Dog tags for dogs
Posted By: Dog tags for dogs | 5.19.2010 at 2:13 PM
I prefer to use a WYSIWYG interface to work rather than to program manually, but I always have to dig in anyway, so this'll help.
#40 notebook adapter manufacturer
Posted By: notebook adapter manufacturer | 5.21.2010 at 1:18 AM
services and most importantly, technical support.
We match the Platform element to the selected item in the c
#41 wholesale shoes
Posted By: wholesale shoes | 5.24.2010 at 3:34 AM
Spring summer pocket perfect supporting role (figure) except heart shape brooch, earring, necklace,
#42 incorporation quebec
Posted By: incorporation quebec | 5.31.2010 at 7:54 PM
I'll put this code to use.
#43 pda data collection
Posted By: pda data collection | 6.10.2010 at 4:32 AM
HI ADMIN,THANKS TO YOU FOR THIS CODE.VERY INFORMATIVE AND USEFUL CONTENTS FOR ME.THANKS
#44 cheap mbt shoes
Posted By: cheap mbt shoes | 6.18.2010 at 9:00 PM
good post!!thank you
#45 chandra mohan
Posted By: chandra mohan | 6.23.2010 at 6:10 AM
plz send me this code
thanks
chandra mohan
#46 tiffany jewelry
Posted By: tiffany jewelry | 7.18.2010 at 11:45 PM
I am really interested in this program but I do not know much about it. After reading your article, i have more experiences to work with it. Your post is interesting and picturesque. I hope i can get your post in next time. Keep on!
#47 tiffany necklace
Posted By: tiffany necklace | 7.18.2010 at 11:45 PM
I am really interested in this program but I do not know much about it. After reading your article, i have more experiences to work with it. Your post is interesting and picturesque. I hope i can get your post in next time. Keep on!
#48 cheap ugg boots
Posted By: cheap ugg boots | 7.18.2010 at 11:45 PM
I am really interested in this program but I do not know much about it. After reading your article, i have more experiences to work with it. Your post is interesting and picturesque. I hope i can get your post in next time. Keep on!
#49 ugg short
Posted By: ugg short | 7.18.2010 at 11:45 PM
I am really interested in this program but I do not know much about it. After reading your article, i have more experiences to work with it. Your post is interesting and picturesque. I hope i can get your post in next time. Keep on!
#50 ghd flat iron
Posted By: ghd flat iron | 7.18.2010 at 11:45 PM
I am really interested in this program but I do not know much about it. After reading your article, i have more experiences to work with it. Your post is interesting and picturesque. I hope i can get your post in next time. Keep on!
#51 ghd hair straightener
Posted By: ghd hair straightener | 7.18.2010 at 11:46 PM
I am really interested in this program but I do not know much about it. After reading your article, i have more experiences to work with it. Your post is interesting and picturesque. I hope i can get your post in next time. Keep on!
#52 tiffany co
Posted By: tiffany co | 7.21.2010 at 2:27 AM
For classic and quality genuine silver jewelry, many people choose Tiffany & Co brand.Now,we present you the hottest Tiffany silver jewelry .get more http://www.tiffanyonsale.com/
#53 tiffany jewelry
Posted By: tiffany jewelry | 7.21.2010 at 2:27 AM
For classic and quality genuine silver jewelry, many people choose Tiffany & Co brand.Now,we present you the hottest Tiffany silver jewelry .get more http://www.tiffanyonsale.com/
#54 tiffany jewellery
Posted By: tiffany jewellery | 7.21.2010 at 2:27 AM
For classic and quality genuine silver jewelry, many people choose Tiffany & Co brand.Now,we present you the hottest Tiffany silver jewelry .get more http://www.tiffanyonsale.com/
#55 tiffany co
Posted By: tiffany co | 7.21.2010 at 2:39 AM
many people choose Tiffany & Co brand.Now For classic and quality genuine silver jewelry, we present you the hottest Tiffany silver jewelry .get more http://www.tiffanyonsale.com/
#56 tiffany jewelry
Posted By: tiffany jewelry | 7.21.2010 at 2:39 AM
many people choose Tiffany & Co brand.Now For classic and quality genuine silver jewelry, we present you the hottest Tiffany silver jewelry .get more http://www.tiffanyonsale.com/
#57 tiffany jewellery
Posted By: tiffany jewellery | 7.21.2010 at 2:39 AM
many people choose Tiffany & Co brand.Now For classic and quality genuine silver jewelry, we present you the hottest Tiffany silver jewelry .get more http://www.tiffanyonsale.com/
#58 congcong
Posted By: congcong | 7.21.2010 at 4:38 AM
[url=http://www.imitatewatch.com/GoodsDetail/Replica-Hublot-Big-Bang-Mens-Watch-301-SB-131-RX-Watches-2213.html]Replica Hublot Big Bang Watches[/url]
[url=http://www.imitatewatch.com/GoodsSeries/Replica-Luminor-Watches-311.html]Replica Panerai Luminor Watches[/url]
[url=http://www.imitatewatch.com/GoodsSeries/Replica-Luminor-Watches-311.html]Patek Philippe Celestial Watches[/url]
[url=http://www.imitatewatch.com/GoodsSeries/Replica-Daytona-Watches-363.html]Replica Rolex Daytona Watches[/url]
[url=http://www.imitatewatch.com/GoodsSeries/Replica-Pilot-Watches-248.html]Replica IWC Pilot Watches[/url]
[url=http://www.imitatewatch.com/GoodsSeries/Replica-Portuguese-Watches-250.html]Replica IWC Portuguese Watches[/url]
[url=http://www.imitatewatch.com/GoodsSeries/Replica-Royal_Oak_Offshore-Watches-29.html]Audemars Piguet Royal Oak Offshore Replica Watches[/url]
[url=http://www.imitatewatch.com/GoodsSeries/Replica-Happy_Sport-Watches-179.html]Chopard Happy Sport Replica Watches[/url]
#59 Internet T1
Posted By: Internet T1 | 7.21.2010 at 5:14 AM
For the beginner its serve as a great tutorial but for me isn't just a tutorial it really matters to me because it give some ideas especially in developing our <a href="http://hubpages.com/hub/t1-provider/">internet t1</a>
#60 tiffany ring
Posted By: tiffany ring | 7.26.2010 at 6:52 AM
Tiffany On Sale Offer a wide range of fashionable Tiffany & Co silver jewelry, including Necklaces, Pendants, Bracelets, Earrings, Rings and Accessories with fantastic discount.more http://www.tiffanyonsale.com/
#61 tiffany bracelet
Posted By: tiffany bracelet | 7.26.2010 at 6:52 AM
Tiffany On Sale Offer a wide range of fashionable Tiffany & Co silver jewelry, including Necklaces, Pendants, Bracelets, Earrings, Rings and Accessories with fantastic discount.more http://www.tiffanyonsale.com/
#62 tiffany necklace
Posted By: tiffany necklace | 7.26.2010 at 6:52 AM
Tiffany On Sale Offer a wide range of fashionable Tiffany & Co silver jewelry, including Necklaces, Pendants, Bracelets, Earrings, Rings and Accessories with fantastic discount.more http://www.tiffanyonsale.com/
#63 Yahoo
Posted By: Yahoo | 7.26.2010 at 8:35 AM
Yahoo! Rocks.
#64 Virginia Beach Maternity Photographer
Posted By: Virginia Beach Maternity Photographer | 7.26.2010 at 7:23 PM
It's my second time around here. so glad that I added you at my feeds. now I can get your updates more quicker.
#65 Raleigh Wedding Photographer
Posted By: Raleigh Wedding Photographer | 7.26.2010 at 7:31 PM
thank you for your help. can I request a discussion for my project?
#66 Virginia Beach Wedding Photographer
Posted By: Virginia Beach Wedding Photographer | 7.26.2010 at 7:36 PM
surprising that there are specific ways to do this codes.
#67 gucci bags
Posted By: gucci bags | 7.29.2010 at 10:50 PM
thank you