Export Datagrid to an xml

Asked by At

Please help me to export a DataGrid to XML. I tried two ways but both cause exceptions to be thrown.

DataTable dt = (DataTable)dataGrid2.DataSource;
dt.WriteXml("t.xml", XmlWriteMode.IgnoreSchema);

This throws an InvalidOperationException with message "Cannot serialize the DataTable. DataTable name is not set."

Please recommend a suitable method to export a datagrid to XML.

2 Answers

0
Marc Gravell On

Given that error; just set the DataTable's name?

dt.TableName = "Fred";
...

Personally, I'd use object-serialization (perhaps XmlSerializer over List<T>), but DataTable should be fine...


Update; for an example using DataTable.WriteXml / ReadXml; note the "THIS LINE MAKES IT ALL WORK" comment; this is necessary a: to be able to write, and b: to read the rows correctly.

using System;
using System.Data;
static class Program
{
    static void Main()
    {
        DataTable table = CreateEmptyTable();
        table.Rows.Add(1, "abc");
        table.Rows.Add(2, "def");
        WriteTable(table);
        table.WriteXml("t.xml", XmlWriteMode.IgnoreSchema);

        DataTable clone = CreateEmptyTable();        
        clone.ReadXml("t.xml");
        WriteTable(clone);
    }
    static DataTable CreateEmptyTable()
    {
        DataTable table = new DataTable();
        table.Columns.Add("Foo", typeof(int));
        table.Columns.Add("Bar", typeof(string));
        table.TableName = "MyTable"; // THIS LINE MAKES IT ALL WORK
        return table;
    }
    static void WriteTable(DataTable table) {
        foreach (DataColumn col in table.Columns)
        {
            Console.Write(col.ColumnName);
            Console.Write('\t');
        }
        Console.WriteLine();
        foreach (DataRow row in table.Rows)
        {
            foreach (DataColumn col in table.Columns)
            {
                Console.Write(row[col]);
                Console.Write('\t');
            }
            Console.WriteLine();
        }
    }
}
0
user1000008 On

This answer is specific to winforms in C# but should apply generally to ASP.NET programming. Below, _dtResults is a global DataTable. Somewhere earlier, when you bind the datagrid (dg) source to the DataTable, just make a copy into the global variable _dtResults. Then call ExportXMLFromDG().

    // user clicks on button, which binds the dg to the datatable,
    // prompts the user to save the XML, serializes it and saves the file.
    private void toolStripButton4_Click(object sender, EventArgs e)
    {
        dg.DataSource = dtResults; // this actually happens earlier.
        _dtResults = dtResults; // this actually happens earlier.

        if (dg.Columns.Count > 0)
        {
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            saveFileDialog1.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*";
            saveFileDialog1.FilterIndex = 1;
            saveFileDialog1.RestoreDirectory = true;

            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                ExportXMLFromDG(saveFileDialog1.FileName);
            }
        }
    }


    private void ExportXMLFromDG(string xml_file)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(DataTable));
        TextWriter textWriter = new StreamWriter(xml_file);
        serializer.Serialize(textWriter, _dtResults);
        textWriter.Close();

    }