Introduction

As you know, XML is a multi-purpose language that is recommended by the World Wide Web Consortium (W3C). It is free, and we can read it in many applications. In this article, I'd like to tell you about the connection between DataGridView and XML file. Usually we use the DataSource from table which we can get from SQL Server database, Oracle, MySQL, or any other database. This time, I'd like to introduce something different. I believe some of you have known this method, but I think it's okay to post this article for beginners. Instead of using a common database language, let's try to use XML.

Using the Code

So let's start making a simple application that uses XML as the database. The example here, which you can download from the attachment, uses one table, that I name as User. That table consists of two columns, one is named user_name, and the other one is user_password.

First, you can look below at the format of user.xml that I use as the DataSource:

In XML, we'd have to make the structure like a tree. It starts with the root (Table), and then the parent (User), and the child (user_name, user_password). From the structure above, we know that we have one table that consists of two columns with two rows of data.

When we execute our code, through the load event, the program will check if the XML file exists, or not. If it does not exist, we should make an empty table. I create a function as shown below. I create 2 parameters, TableName and ColumnNames that I declare as a ParamArray. ParamArray, if you haven't known this kind of type, is a parameter that can catch multi-values. Okay, back to the topic. When the program knows that we don't have the file, it will call this function. This will create the tree-structured XML, with an empty string value, that is used only as an initialization.

For the explanation of code above, we create xmlFile based on the content of the file that we have before. Then read it and save it into the dataset. Just don't forget to close the xmlFile, because if you do, there will be an error saying that the file is currently used by another application. After we get the dataset, we call the first table inside. Since we only have one table, and we'd like to call that first table, we call it using command .Tables(0) on the DataSet.

Run it, and you have a DataGridView with an XML datasource. Now what next? After we can select the data, how do you update the data? You can use a simple command that I provide below.

Share

About the Author

Indra Permana Rusli is a freshgraduate, has experience and knowledge in using multimedia softwares, developing website using PHP, and currently working using VB.NET in his company to develop ERP software.