This tutorial will show you how to create a Windows Application that can read the contents of an XML file, and also how to filter the contents of an XML file to display only the data we want. VB version.

WinForms are the Windows Applications we can create in Visual Studio. In this tutorial, we will explore how we can use an XML file to store data and also use a WinForm to extract this data and display it on our form, as well as filtering the data so we can view just what we want to.

The first thing we will do is to create a sample XML file, or if you have one already you can use that one.

We will create an XML file with people’s names, city and age. The XML file will look like this:

We can now start designing our Form. We are going to implement two buttons, a ComboBox, a RichTextBox, and a label. One button will retrieve all the data from the XML file and display it in the RichTextBox, the other button will retrieve the data that matches our ComboBox and display it in the RichTextBox, and the ComboBox will display all the Cities in the XML file, so we can filter the data by City. The form will look something like this:

Once we have our form designed, we can double-click on a blank area of the form to create a Form_Load event in the code-behind, and we will create a method for the ComboBox to be populated. The code for this method looks something like this:

This method loads our XML file and selects the node that our data (City) is at. Then, for each node in our selected node list, we will add the City item to our ComboBox – but only if it has not already been added. This will avoid duplicates in the ComboBox.

Next, we can double-click our first button in design view to write the code for that. We will want to select all the data from the XML file and output it to the RichTextBox. The code for this button will look something like this:

This block of code loads our XML file, then we use LINQ to select all the data from within, then simply loop through the data and output it to our RichTextBox. The n escape sequence will output a new line in our text box.

We can use a similar block of code for our other button, but instead of selecting all the data from the XML file, we will use a WHERE clause in the LINQ code to select only the XML data that matches our requirements (our selected item from the ComboBox). The code will look like this:

As you can see, this code block is identical with the exception of the WHERE clause in the LINQ Select statement. We are only selecting the data which matches our selection from the ComboBox. Now if we run this application, we will be able to load the entire XML file into the textbox, and also filter the data by our Combo Box.

The entire code-behind is as follows:

Download Source Files