Solved

Export DataGrid to XML or update data in the dataset and then export to XML

Posted on 2006-06-14
3
690 Views
Last Modified: 2011-09-20
I need to know how to either export my datagrid directly to an xml file (preferred) or modify specific items within the dataset and then export the xml.

0
Comment
Question by:JPERKS1985
  • 2
3 Comments
 
LVL 18

Accepted Solution

by:
vbturbo earned 500 total points
Comment Utility
Hi

try this

Imports System
Imports System.Xml
Imports System.Data

Dim dsXmlData As DataSet = New DataSet
Dim strXmlFileName As String = "c:\back.xml"

   Private Sub ProgramLoad(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Me.Text = "XML to Dataset to DataGrid Example"
        Call CreateDataSource()

    End Sub

    Private Sub CreateDataSource()
        'open the xml data file
        Try
            dsXmlData.ReadXml(strXmlFileName)                               'assign the xml file to the dataset
            DataGrid1.DataSource = dsXmlData.Tables(0).DefaultView          'assign the dataset to the grids data source

            DataGrid1.DataSource.AllowNew = True                            'the add a row button still works when this is set to false
        Catch ex As System.IO.FileNotFoundException

            If CreateXmlFile() = False Then                                 'try to create the file and continue if sucesful
                MsgBox("XML file was not found")                            'something failed so we must end
                End
            End If

        End Try

    End Sub

    Private Sub AddNewRow(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddRow.Click
        'when the button is clicked a rows worth of data will be added to the dataset and then written to the xml file

        Dim drnewRow As DataRow                                 'create a new datarow

        drnewRow = dsXmlData.Tables(0).NewRow()                 'assign it to our data table

        drnewRow("Type") = "File"                               'add populate it with some data
        drnewRow("Path") = "C:\hello.txt"
        drnewRow("Destination") = "D:\Backup"
        drnewRow("Id") = "5"

        dsXmlData.Tables(0).Rows.Add(drnewRow)                  'add the new data to the table/dataset

        dsXmlData.AcceptChanges()                               'and accept the addition

        'and then write it out to the xml file
        dsXmlData.WriteXml(strXmlFileName, XmlWriteMode.WriteSchema)

    End Sub

    Private Sub ProgramUnload(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Closed

        'if the dataset has been updated save the changes to the xml file
        If dsXmlData.HasChanges = True Then dsXmlData.WriteXml(strXmlFileName, XmlWriteMode.WriteSchema)

    End Sub

    Private Function CreateXmlFile() As Boolean
        'this will create the xml file, save it and attach it to the grid via the dataset
        'this is not the best way of doing it though. for one the ID is now a column and not an attribute of the row
        Try

            Dim dtNewRow As DataTable                               'create a table for the new row

            dtNewRow = dsXmlData.Tables.Add("Backups")              'add the table to the DataSet

            Dim c1 As New DataColumn("Type")                        'create each column in the table
            c1.DataType = System.Type.GetType("System.String")      'and set the type
            Dim c2 As New DataColumn("Path")
            c2.DataType = System.Type.GetType("System.String")      'i was having problems doing both in one line
            Dim c3 As New DataColumn("Destination")                 'it would gpf on some of them and always on the boolean
            c3.DataType = System.Type.GetType("System.String")
            Dim c4 As New DataColumn("Id")


            dtNewRow.Columns.Add(c1)                                'add the columns to the table
            dtNewRow.Columns.Add(c2)
            dtNewRow.Columns.Add(c3)
            dtNewRow.Columns.Add(c4)

            Dim drnewRow As DataRow                                 'create a new datarow

            drnewRow = dtNewRow.NewRow()                            'assign it to our data table

            drnewRow("Type") = "File"                               'add populate it with some data
            drnewRow("Path") = "C:\hello.txt"
            drnewRow("Destination") = "D:\Backup"
            drnewRow("Id") = "1"

            dtNewRow.Rows.Add(drnewRow)                             'add the new data to the table

            dsXmlData.AcceptChanges()                               'and accept the addition

            'and then write it out to the xml file
            dsXmlData.WriteXml(strXmlFileName, XmlWriteMode.WriteSchema)

            DataGrid1.DataSource = dsXmlData.Tables(0).DefaultView          'assign the dataset to the grids data source

        Catch ex As Exception
            Return False                'return a flase and just bail out
        Finally
            CreateXmlFile = True        'return true if all worked fine
        End Try

    End Function

hope this helps

rgds vbturbo
0
 
LVL 18

Expert Comment

by:vbturbo
Comment Utility
BTW

if u wonna know about dataset's and how to work  with dataset u might checkout this link

http://www.homeandlearn.co.uk/NET/nets12p9.html
0
 
LVL 9

Expert Comment

by:lojk
Comment Utility
I would think serialisation would be the way to go.... (because it just is, usually)

Pass your dataset into and outof these functions, they return the DS as text that you can save or whatever.
You may like to modify them to read and write directly to files..

      Public Function SerializeDataset(ByVal DatasetToSerialise As Data.Dataset) As String
        Dim oXS As System.Xml.Serialization.XmlSerializer
        Try
            oXS = New System.Xml.Serialization.XmlSerializer(GetType(Data.Dataset))
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
        Dim oStmW As IO.StringWriter
        oStmW = New IO.StringWriter()
      Try
            oXS.Serialize(oStmW, DatasetToSerialise)
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
        oStmW.Close()

        Return oStmW.ToString

    End Function



    Public Function DeserialiseDataset(ByVal SerializedObject As String) As DataSet
        Dim oXS As Xml.Serialization.XmlSerializer = New Xml.Serialization.XmlSerializer(GetType(Data.DataSet))
        Dim oStmR As IO.StringReader
        oStmR = New IO.StringReader(SerializedObject)
        Dim NewDataSet As Data.DataSet= CType(oXS.Deserialize(oStmR), Data.DataSet)
        oStmR.Close()
        Return NewDataSet
    End Function



0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Suggested Solutions

The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
This video discusses moving either the default database or any database to a new volume.
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now