【发布时间】: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 文件中而不覆盖旧数据