views:

47

answers:

3

I am having problems to write DataTable to XML document and read back the same XML document to the DataTable.

The Following is the Code, please help. Thanks in advance.
//TO READ A FILE

       if (openFileDialog1.ShowDialog() == DialogResult.OK) 
       {              
            myDT_For_DGV.ReadXml(@openFileDialog1.FileName);
            //MessageBox.Show(openFileDialog1.FileName);

        }

//TO WRITE TO XML
if (myDT_For_DGV.Rows.Count != 0)
        {
            saveFileDialog1.ShowDialog();
            saveFileDialog1.FileName = "checkOutFile.xml";
            myDT_For_DGV.TableName = "CheckOutsAndIns";
            myDT_For_DGV.WriteXml(saveFileDialog1.FileName, true);
        }
A: 

you should be using DataSet, not DataTable.

Muad'Dib
A: 

I think you're looking for the XmlWriteMode.WriteSchema flag. Here's a working example:

string path = @"foo.xml";

if (!File.Exists(path))
{
    DataTable newtable = new DataTable("mytable");
    newtable.Columns.Add("Fruit");
    DataRow newrow = newtable.NewRow();
    newrow[0] = "Banana";
    newtable.Rows.Add(newrow);
    newtable.WriteXml(path, XmlWriteMode.WriteSchema);
    Console.WriteLine(File.ReadAllText(path)); // BANANA!
}

DataTable dt = new DataTable();
dt.ReadXml(path);
dt.Rows[0][0] = "Apple";
dt.WriteXml(path, XmlWriteMode.WriteSchema);
Console.WriteLine(File.ReadAllText(path)); // APPLE!
xcud
A: 

I fixed it, The Problem is, the tablename was assigned while saving but not while reading. So assign the table name globally, which will let it read and write without any problem.

so the code will be,

myDT_For_DGV.TableName = "CheckOutsAndIns";

if (openFileDialog1.ShowDialog() == DialogResult.OK) 
       {              
              myDT_For_DGV.ReadXml(@openFileDialog1.FileName);
            //MessageBox.Show(openFileDialog1.FileName);

        }

//TO WRITE TO XML
if (myDT_For_DGV.Rows.Count != 0)
        {
            saveFileDialog1.ShowDialog();
            saveFileDialog1.FileName = "checkOutFile.xml";
            myDT_For_DGV.WriteXml(saveFileDialog1.FileName, true);
        }
Yash