Working with XML in Windows Forms Application in C# - Part 1

Category: .NET Framework

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.


[Click to enlarge]

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


[Click to enlarge]

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!


Grand Theft Auto IV
XBOX360

Metal Gear Solid 4
PS3

FIFA 08
PC

Guitar Hero III
Wii

Halo 3
XBOX360

Wii Sports
Wii

FIFA 08
PS3

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.


[Click to enlarge]

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.

private void butGetAll_Click(object sender, EventArgs e)
{
XDocument xmlDoc = XDocument.Load("VideoGames.xml");

var games = from game in xmlDoc.Descendants("Game")
select new
{
Title = game.Element("Title").Value,
Platform = game.Element("Platform").Value,
};

txtResults.Text = "";
foreach (var game in games)
{
txtResults.Text = txtResults.Text + "Title: " + game.Title + "\n";
txtResults.Text = txtResults.Text + "Platform: " + game.Platform + "\n\n";
}

if (txtResults.Text == "")
txtResults.Text = "No Results.";
}

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 Form1_Load(object sender, EventArgs e)
{
populateCombo();
}

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);
}

 

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.

private void butFilter_Click(object sender, EventArgs e)
{
XDocument xmlDoc = XDocument.Load("VideoGames.xml");

var games = from game in xmlDoc.Descendants("Game")
where game.Element("Platform").Value == cmbPlatform.SelectedItem.ToString()
select new
{
Title = game.Element("Title").Value,
Platform = game.Element("Platform").Value,
};

txtResults.Text = "";
foreach (var game in games)
{
txtResults.Text = txtResults.Text + "Title: " + game.Title + "\n";
txtResults.Text = txtResults.Text + "Platform: " + game.Platform + "\n\n";
}

if (txtResults.Text == "")
txtResults.Text = "No Results.";
}

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



Download Project Source - Enter your Email to be emailed a link to download the Full Source Project used in this Tutorial!



100% SPAM FREE! We will never sell or rent your email address!