Friday, April 8, 2011

Export Datagrid to an xml

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.

From stackoverflow
  • 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();
            }
        }
    }
    
    Arunachalam : this is not working again same error how to serialize can u explain in detail
  • Here's a link to an example of what Marc suggests.

    Scroll down to the sample's SerializeToXML and DeserializeFromXML methods.

0 comments:

Post a Comment