Click here to Skip to main content
15,867,568 members
Articles / Programming Languages / XML

Using XML as datagridview Source

Rate me:
Please Sign up or sign in to vote.
4.09/5 (8 votes)
15 Jan 2009CPOL3 min read 98K   6.3K   28   10
An article about linking datagridview with XML file

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:

XML
<?xml version="1.0" standalone="yes"?>
<Table>
  <User>
    <user_name>admin</user_name>
    <user_password>indrapr</user_password>
  </User>
  <User>
    <user_name>user</user_name>
    <user_password>indrapr</user_password>
  </User>
</Table> 

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.

VB.NET
Private Function CreateEmptyTable(ByVal TableName As String, _
	ByVal ParamArray ColumnNames() As String) As Boolean
  Dim writer As New XmlTextWriter(filePath, System.Text.Encoding.UTF8)

  Try
    writer.WriteStartDocument(True)
    writer.Formatting = Formatting.Indented
    writer.Indentation = 2
    writer.WriteStartElement("Table")
    writer.WriteStartElement(TableName)
    For Each ColumnName As String In ColumnNames
      writer.WriteStartElement(ColumnName)
      writer.WriteString(String.Empty)
      writer.WriteEndElement()
    Next
    writer.WriteEndElement()
    writer.WriteEndElement()
    writer.WriteEndDocument()
    writer.Close()
  Catch ex As Exception
    MsgBox("Cannot create new table.")
    Return False
  End Try

  Return True
End Function

Then after running the validation above, we'll read the content of the XML, and make it as the DataSource of the DataGridView that we have in our form.

VB.NET
xmlFile = XmlReader.Create(filePath, New XmlReaderSettings())
ds.ReadXml(xmlFile)
xmlFile.Close()

Me.DgvMstUser.DataSource = ds.Tables(0)

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.  

VB.NET
Dim dt As New DataTable

dt = Me.DgvMstUser.DataSource
dt.WriteXml(filePath)

We create a new DataTable object, get the DataSource table from the DataGridView, and write it as an XML.  

And that's all. Congratulations, you have made a simple application using an XML database. If you have any questions about this article, feel free to email me or post your comments.

History

  • 15th January, 2009: Initial post 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Junior) PT. Televisi Transformasi Indonesia
Indonesia Indonesia
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.

Comments and Discussions

 
GeneralWonderful Pin
mrtq1327-Feb-13 18:59
mrtq1327-Feb-13 18:59 
GeneralMy vote of 5 Pin
sdgrfghdhsdgs6-Aug-12 20:04
sdgrfghdhsdgs6-Aug-12 20:04 
QuestionDemo project files not writing into XML. Pin
gs_virdi23-May-11 1:21
gs_virdi23-May-11 1:21 
AnswerRe: Demo project files not writing into XML. Pin
GrG8-May-12 20:25
GrG8-May-12 20:25 
Generalit's wonderful!!! Pin
chenlulouis29-Jun-10 20:42
chenlulouis29-Jun-10 20:42 
QuestionLinq over XML? Pin
Pat Tormey20-Jan-09 0:43
Pat Tormey20-Jan-09 0:43 
GeneralMy vote of 2 Pin
ProJester115-Jan-09 11:05
ProJester115-Jan-09 11:05 
GeneralRe: My vote of 2 Pin
saini arun16-Jan-09 19:02
saini arun16-Jan-09 19:02 
GeneralRe: My vote of 2 Pin
Jon_Boy9-Feb-09 7:16
Jon_Boy9-Feb-09 7:16 
QuestionFuture Article? Pin
MotoZarkov4215-Jan-09 7:48
MotoZarkov4215-Jan-09 7:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.