开发者

Convert DataTable to XML file and viceversa

I am having a problem with reading an XML file onto a DataTable. Initially, I am writing a Datatable to an XML file and saving it. Now, when I want to read the XML file back to the DataTable, it's not happening.

The following code is for writing the file:

private void saveAsToolStripMenuItem_Click(object sender, EventArgs e) 
{
    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);
    }
    else
    {
        MessageBox.Show("Please add licences to DataGridView, you havent added any licences as of now", "Alert");
    }
}

And for reading the file:

private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
    //write code to open file
    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        //myFile = openFileDialog1.FileName;
        System.IO.MemoryStream xmlStream = new System.IO.MemoryStream();

        xmlStream.Position = 0;

        myDT_For_DGV.ReadXml(openFileDialog1.FileName);
        //Me开发者_运维问答ssageBox.Show(openFileDialog1.FileName);
    }
}


It might be easier to just work with the higher-level DataSet, like this:

DataSet dataSet = new DataSet();
DataTable dataTable = new DataTable();

dataSet.Tables.Add(dataTable);
// Save to disk
dataSet.WriteXml(@"C:\MyDataset.xml");

// Read from disk
dataSet.ReadXml(@"C:\MyDataset.xml");


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);
        }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜