Link to home
Start Free TrialLog in
Avatar of Victor  Charles
Victor CharlesFlag for United States of America

asked on

Help with saving DataGridView data to xml file

I am loading a DatagridView with data from a datatable, when I update the DatagridView how do I save the changes to an xml file using VB.NET (Windows App)?

Thanks,

Victor
ASKER CERTIFIED SOLUTION
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Victor  Charles

ASKER

Hi Fernando,

When I change the data in the Gnid and press Save, wil the changes be saved in he xml file? No access to app to  test your cide at the moment.

Thanks

V.
        '' When ready to save the DataTable with its [b][u]update[/u][/b] jus do this.
        dt.WriteXml("SavedToDisk.xml")

Open in new window


Where dt in your code is your DataTable.
I will be loading the grid from an xml file, i think the key is to include  Dim bs As New BindingSource with the DataTable in order to save changes in Grid to the xml file.
This is code I just written and tested:

    Private Sub btnGenerate_Click(sender As Object, e As EventArgs) Handles btnGenerate.Click
        'Create a table
        Dim dt As New DataTable("Person")
        With dt
            .Columns.Add("FirstName", GetType(String))
            .Columns.Add("LastName", GetType(String))


            'Add rows
            .LoadDataRow(New Object() {"Joe", "Dalton"}, True)
            .LoadDataRow(New Object() {"Jack", "Dalton"}, True)
            .LoadDataRow(New Object() {"Willam", "Dalton"}, True)
            .LoadDataRow(New Object() {"Averel", "Dalton"}, True)
        End With

        dt.WriteXml("data.xml", XmlWriteMode.WriteSchema)
    End Sub

    Private Sub btnLoad_Click(sender As Object, e As EventArgs) Handles btnLoad.Click
        dim ds as New DataSet
        ds.ReadXml("data.xml", XmlReadMode.ReadSchema)
        DataGridView1.DataSource = ds.tables(0)
    End Sub

    Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
        dim dt As DataTable = TryCast(DataGridView1.DataSource, DataTable)
        dt.WriteXml("data.xml", XmlWriteMode.WriteSchema)
    End Sub

Open in new window

Thank You.
Not a problem Victor, glad to help.