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

查看:44
本文介绍了将 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.

以下代码用于写入文件:

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

用于读取文件:

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 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天全站免登陆