【问题标题】:How to avoid overwriting my xml database? [closed]如何避免覆盖我的 xml 数据库? [关闭]
【发布时间】:2017-05-31 15:56:35
【问题描述】:

我正在尝试编写一个 WinForms 应用程序,该应用程序从数据网格中获取数据并将其附加到 xml 文件中,但我的代码正在覆盖现有数据。

我通过从文本框中读取值将数据添加到数据网格

    private void add_row_BTN_Click(object sender, EventArgs e)
    {
        int add = dataGridView1.Rows.Add();
        dataGridView1.Rows[add].Cells[0].Value = textBox1.Text;
        dataGridView1.Rows[add].Cells[1].Value = textBox2.Text;
        dataGridView1.Rows[add].Cells[2].Value = textBox4.Text;
        dataGridView1.Rows[add].Cells[3].Value = textBox5.Text;
        dataGridView1.Rows[add].Cells[4].Value = textBox6.Text;
        dataGridView1.Rows[add].Cells[5].Value = textBox3.Text;
    }

这里是我保存 DataGridView 数据的地方

    private void save_BTN_Click(object sender, EventArgs e)
    {
        DataSet ds = new DataSet();
        DataTable dt = new DataTable();
        dt.TableName = "Employees";
        dt.Columns.Add("Name");
        dt.Columns.Add("E-Mail");
        dt.Columns.Add("Age");
        dt.Columns.Add("WorkHours");
        dt.Columns.Add("Gender");
        dt.Columns.Add("JobTitle");
        ds.Tables.Add (dt);
        DataRow dr = ds.Tables["Employees"].NewRow();
        dr["Name"] = textBox1.Text;
        dr["E-Mail"] = textBox2.Text;
        dr["Age"] = textBox4.Text;
        dr["WorkHours"] = textBox5.Text;
        dr["Gender"] = textBox6.Text;
        dr["JobTitle"] = textBox3.Text;
        ds.Tables["Employees"].Rows.Add(dr);

        ds.WriteXml("Data.xml");

    }

【问题讨论】:

  • 想要它做什么?你以前的数据应该怎么做,你的新数据应该怎么做?显然,它们不能共享相同的文件名。
  • 我希望程序从文本框中获取数据并将其保存到 XML 文件中而不覆盖旧数据

标签: c# xml winforms ado.net


【解决方案1】:

您可以使用 Overload 方法输入如下

System.IO.FileStream stream = new System.IO.FileStream(@"Data.xml", System.IO.FileMode.Append);

            // Write to the file with the WriteXml method.
            ds.WriteXml(stream);

【讨论】:

  • 我试过了,它可以工作,但是我必须关闭并打开程序才能输入新数据
  • 使用后调用stream.close()关闭流。
猜你喜欢
  • 1970-01-01
  • 2015-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-10
  • 2015-05-15
  • 1970-01-01
  • 2021-04-18
相关资源
最近更新 更多