简体   繁体   English

c#将DataGridView保存到Xml文件

[英]c# Save DataGridView to Xml file

This is my button to save file: 这是我保存文件的按钮:

private void metroButton12_Click(object sender, EventArgs e) // save
{
    DataSet ds = (DataSet)dataGridView1.DataSource;
    SaveFileDialog sfd = new SaveFileDialog();
    sfd.Filter = "XML|*.xml";
    if (sfd.ShowDialog() == DialogResult.OK)
    {
        try
        {
            ds.Tables[0].WriteXml(sfd.FileName);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
    }
}

I try to safe my datagridview to XML but nothing happpend when I choose file. 我尝试将我的datagridview保护为XML,但是当我选择文件时没有任何好处。 When I start console I see this: System.NullReferenceException: The object reference was not set to an object instance. 当我启动控制台时,我看到:System.NullReferenceException:对象引用未设置为对象实例。

My gridview look like: ID Name 1 Michale 2 Noob 我的gridview看起来像:ID名称1 Michale 2 Noob

What am I doing here wrong?.. I saw a lot of thing's on the web but could not find any solutions in stackoverflow and other forums. 我在这里做错了什么?我在网上看到很多东西但在stackoverflow和其他论坛中找不到任何解决方案。 Please be patient for newbie guys. 请耐心等待新手们。 Thank you! 谢谢!

To me it sounds like your problem is not where you think it is. 对我而言,你的问题听起来并不像你认为的那样。

when i start console i see this : System.NullReferenceException: The object reference was not set to an object instance. 当我启动控制台时,我看到:System.NullReferenceException:对象引用未设置为对象实例。

To me you are implying that you get the message when you launch the application, not when you click the button. 对我来说,暗示您在启动应用程序时收到消息,而不是在您单击按钮时收到消息。 If you get the error before you click, your problem is elsewhere and not in the code snippet you posted. 如果您在单击之前收到错误,则问题出在其他地方,而不是在您发布的代码段中。 Here is a complete and testable snippet of what you are currently doing. 这是您目前正在做的完整且可测试的片段。

using System;
using System.Data;
using System.Windows.Forms;

namespace DataGridViewToXML_43053387
{
    public partial class Form1 : Form
    {
        //DataSet theDataSet;
        public Form1()
        {
            InitializeComponent();
            InsertDgvIntoForm();
            ExportDgvToXML();
        }

        private void InsertDgvIntoForm()
        {
            //create a data set
            DataSet ds = new DataSet();
            //create a data table for the data set
            DataTable dt = new DataTable();
            //create some columns for the datatable
            DataColumn dc = new DataColumn("ItemName");
            DataColumn dc2 = new DataColumn("ItemValue");
            DataColumn dc3 = new DataColumn("Blah");
            DataColumn dc4 = new DataColumn("Bleh");
            //add the columns to the datatable
            dt.Columns.Add(dc);
            dt.Columns.Add(dc2);
            dt.Columns.Add(dc3);
            dt.Columns.Add(dc4);

            //create 5 rows of irrelevant information
            for (int i = 0; i < 5; i++)
            {
                DataRow dr = dt.NewRow();
                dr["ItemName"] = "Item" + i + "Name";
                dr["ItemValue"] = "Item" + i + "Value";
                dr["Blah"] = "Item" + i + "Blah";
                dr["Bleh"] = "Item" + i + "Bleh";
                dt.Rows.Add(dr);
            }
            //add the datatable to the datasource
            ds.Tables.Add(dt);
            //just because it looks better on my screen
            dataGridView1.AutoSize = true;
            //make this data the datasource of our gridview
            dataGridView1.DataSource = ds.Tables[0];

        }

        private void ExportDgvToXML()
        {
            DataTable dt = (DataTable)dataGridView1.DataSource;
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "XML|*.xml";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    dt.WriteXml(sfd.FileName);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }
        }
    }
}

blaze_125 answer didn't help me so I've found this solution: blaze_125回答没有帮助我所以我找到了这个解决方案:

private void btnXML_Save_Click(object sender, EventArgs e)
{
    DataTable dt = new DataTable();
    dt.TableName = "Bank";

    for (int i = 0; i < dataGridView1.Columns.Count; i++)
    {
        //if (dataGridView1.Columns[i].Visible) // Add's only Visible columns (if you need it)
        //{
            string headerText = dataGridView1.Columns[i].HeaderText;
            headerText = Regex.Replace(headerText, "[-/, ]", "_");

            DataColumn column = new DataColumn(headerText);
            dt.Columns.Add(column);
        //}
    }

    foreach (DataGridViewRow DataGVRow in dataGridView1.Rows)
    {
        DataRow dataRow = dt.NewRow();
        // Add's only the columns that you want
        dataRow["BLZ"] = DataGVRow.Cells["BLZ"].Value;
        dataRow["Test_1"] = DataGVRow.Cells["Test 1"].Value;
        dataRow["Test_2"] = DataGVRow.Cells["Test-2"].Value;
        dataRow["PIN_TAN_Test_URL"] = DataGVRow.Cells["PIN/TAN-Test URL"].Value;

        dt.Rows.Add(dataRow); //dt.Columns.Add();
    }
    DataSet ds = new DataSet();
    ds.Tables.Add(dt);

    //Finally the save part:
    XmlTextWriter xmlSave = new XmlTextWriter(XML_Save_Path_Filename, Encoding.UTF8);
    xmlSave.Formatting = Formatting.Indented;
    ds.DataSetName = "Data";
    ds.WriteXml(xmlSave);
    xmlSave.Close();
}

Result will look like this: 结果将如下所示:

<Data>
  <Bank>
    <BLZ>10000001</BLZ>
    <Test_1>server.bank.com</Test_1>
    <Test_2>V3.0</Test_2>
    <PIN_TAN_Test_URL>https://test.bank.com/</PIN_TAN_Test_URL>
  </Bank>
  ....
  <Bank>
    <BLZ>12396123</BLZ>
    <HBCI_Zugang_DNS>test01.test.com</HBCI_Zugang_DNS>
    <HBCI_Version>V3.0</HBCI_Version>
    <PIN_TAN_Test_URL>https://test11.test.com</PIN_TAN_Test_URL>
  </Bank>
</Data>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM