将DataTable转换为XML文件,反之亦然 [英] Convert DataTable to XML file and viceversa

查看:105
本文介绍了将DataTable转换为XML文件,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将XML文件读取到 DataTable 时遇到问题。最初,我将 Datatable 写入XML文件并保存。现在,当我想将XML文件读回到 DataTable 时,它没有发生。

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.

以下代码

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

并用于读取文件:

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);
        //MessageBox.Show(openFileDialog1.FileName);
    }
}


推荐答案

I修复了问题,问题是,表名是在保存时分配的,而不是在读取时分配的。因此,请全局分配表名,这样便可以毫无问题地对其进行读写。

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.

因此代码为

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

这篇关于将DataTable转换为XML文件,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆