Thursday, July 29, 2010

Roundtrip XML - Datagrid

What are we cooking today?
Need to load from XML into a datagridview, allow the user to modify the gridview and then copy from the datagridview back into the same XML document.

RECIPE


Imports System.Data
Imports System.Xml

From XML to datagridview
  Try
           Dim  strPathToXML as string = "...path to Xml doc .../myXML.xml"
           Dim xmlFile As XmlReader
           Dim ds As New DataSet

            xmlFile = XmlReader.Create(strPathToXML, New XmlReaderSettings())
            ds.ReadXml(xmlFile)
            myDataGrid.DataSource = ds.Tables(0)
             xmlFile.Close() '---you need this closed to be able to write

        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try


Let the user modify the datagridview
Here modify a value in the DataGridview


From datagridview to XML 
   Dim mydataset As New DataSet
        Try
            mydataset = DatagridviewToDataset(myDataGrid)
            mydataset.WriteXml(strPathToXML) 
 
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try


    
 Function DatagridviewToDataset 
Public Function DatagridviewToDataset(ByVal dgv As DataGridView) As System.Data.DataSet
        Dim ds As New DataSet
      
        Try
            '---Add a new table to the dataset
            ds.Tables.Add("myTable")

            '---Add the columns
            Dim col As System.Data.DataColumn

            '---For each colum in the datagridveiw add a new column to your table
            For Each dgvCol As DataGridViewColumn In dgv.Columns
                col = New System.Data.DataColumn(dgvCol.Name)
                ds.Tables("myTable").Columns.Add(col)
            Next

            '---Add the rows from the datagridview
            Dim row As System.Data.DataRow
            Dim colcount As Integer = dgv.Columns.Count - 1

            For i As Integer = 0 To dgv.Rows.Count - 1
                row = ds.Tables("myTable").Rows.Add

                For Each column As DataGridViewColumn In dgv.Columns
                    row.Item(column.Index) = dgv.Rows.Item(i).Cells(column.Index).Value
                Next

            Next

            Return ds
        Catch ex As Exception
            MessageBox.Show("Error Converting from DataGridView" & ex.InnerException.ToString, _
            "Error Converting from DataGridView", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return Nothing
        End Try
    End Function


Enjoy it!