我需要帮助从datagridview创建一个xml文件

时间:2016-07-13 14:28:32

标签: xml vb.net visual-studio datagridview export

我正在尝试生成一个程序,它允许您将数据行生成到datagridview中,它允许您将datagridview导出到xml文件或从xml导入数据。我已经弄清楚如何打开一个xml文件并将其写入datagridview,但我很难搞清楚如何将它保存到xml上。

我正在使用的代码来自http://www.v-basic.net/2011/04/xml-import-and-export.html并且它一直出现错误" my_datatable.WriteXml(save_file.FileName)"每次我尝试通过覆盖文本文件来保存数据库。

以下是代码:

    Imports System.Xml
    Imports System.Data

Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    'create a openfile dialog
    Dim open_file As New OpenFileDialog

    'give its filter
    open_file.Filter = "Files (*.xml) | *.xml"
    Try
        'if ok click at opendialog
        If open_file.ShowDialog() = DialogResult.OK Then
            Dim xmlFile As XmlReader
            xmlFile = XmlReader.Create(open_file.FileName, New XmlReaderSettings()) 'get xml data from the path

            Dim ds As New DataSet
            ds.ReadXml(xmlFile) 'read xml data
            'show xml data in datagridview
            DataGridView1.DataSource = ds.Tables(0)
        End If

    Catch ex As Exception
        'if any problem show error
        MsgBox(ex.Message)
    End Try
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    'define a save dialog
    Dim save_file As New SaveFileDialog
    save_file.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*" 'give its extension
    save_file.FilterIndex = 2 'select xml

    Dim my_datatable As New DataTable 'create a datatable
    If save_file.ShowDialog() = DialogResult.OK Then 'if ok click

        'get datagridview source to datatable
        my_datatable = CType(DataGridView1.DataSource, DataTable)

        'save datatable with xml format
        my_datatable.WriteXml(save_file.FileName)
    End If
End Sub
End Class

如果有人解决了这个问题,我将非常感激,或者如果有一个替代解决方案将datagridview行保存到xml文件上,那么我将非常感谢您的代码

0 个答案:

没有答案