Click here to Skip to main content
15,892,927 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 99K   6.3K   28  
An article about linking datagridview with XML file
'Copyright� 2009. Indra Permana Rusli

Imports System.Xml
Imports System.IO

Public Class frmMain
    Private filePath As String = "C:\user.xml" 'xml filepath

#Region " User Defined Function "

    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

    Private Function FormatDgvMstUser(ByRef ObjDgv As DataGridView) As Boolean
        Dim cUsername As New DataGridViewTextBoxColumn
        Dim cPassword As New DataGridViewTextBoxColumn

        cUsername.Name = "user_name"
        cUsername.HeaderText = "Username"
        cUsername.Width = 100
        cUsername.DataPropertyName = "user_name"
        cUsername.Visible = True
        cUsername.ReadOnly = False

        cPassword.Name = "user_password"
        cPassword.HeaderText = "Password"
        cPassword.Width = 100
        cPassword.DataPropertyName = "user_password"
        cPassword.Visible = True
        cPassword.ReadOnly = False

        Try
            ObjDgv.Columns.Clear()
            ObjDgv.Columns.AddRange(New DataGridViewColumn() {cUsername, cPassword})
            ObjDgv.AllowUserToAddRows = True
        Catch ex As Exception
            MsgBox("Cannot format datagridview.")
            Return False
        End Try

        Return True
    End Function

#End Region

    Private Sub frmMain_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim xmlFile As XmlReader
        Dim ds As New DataSet

        'if file doesn't exist, create the file with its default xml table
        If Not File.Exists(filePath) Then
            If Not Me.CreateEmptyTable("User", "user_name", "user_password") Then End
        End If

        'fill dataset with selected xml table
        xmlFile = XmlReader.Create(filePath, New XmlReaderSettings())
        ds.ReadXml(xmlFile)
        xmlFile.Close()

        'init datagridview
        Me.DgvMstUser.DataSource = ds.Tables(0)
        If Not Me.FormatDgvMstUser(Me.DgvMstUser) Then End
    End Sub

    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Dim dt As New DataTable

        Me.DgvMstUser.EndEdit()
        dt = Me.DgvMstUser.DataSource

        Try
            dt.WriteXml(filePath)
            MsgBox("Data has been saved.")
        Catch ex As Exception
            MsgBox("Data cannot be saved.")
        End Try
    End Sub
End Class

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

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