如何在xml文件中选择和更新信息

时间:2017-07-08 15:36:07

标签: c# xml

所以我知道如何将所选网格视图中的数据加载到文本框中,但我如何制作它以便更新所选的地点信息,而不是在文件中创建一个新的位置,还要从中删除选定的地点文件,如果我想。

这就是我目前加载到datagrid的方式

ds.ReadXml("Database.xml");

string filter = "";
filter = "userdata" + " LIKE '*" + "u" + "*'";
DataView dv = new DataView(ds.Tables[0]);
dv.RowFilter = filter;
dataGridView1.DataSource = dv;
dataGridView1.Columns[4].Visible = false;

以及我如何根据点击的文本框加载

if (e.RowIndex >= 0)
{

DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
Nametb.Text = row.Cells["name"].Value.ToString();
Locationtb.Text = row.Cells["Location"].Value.ToString();
Infotb.Text = row.Cells["Info"].Value.ToString();
dayvisitcb.Text = row.Cells["Dayvisited"].Value.ToString();

}

这是我的xml

<root>
  <place>
    <Name>home</Name>
    <Location>x-292 z 277</Location>
    <Info>home</Info>
    <Dayvisited>10</Dayvisited>
  </place>
  <place>
    <Name>town</Name>
    <Location>x 990 z-2485</Location>
    <Info>gas station</Info>
    <Dayvisited>12</Dayvisited>
  </place>
  <place>
    <Name>crossing</Name>
    <Location>x 90 z-2998</Location>
    <Info>working stiff</Info>
    <Dayvisited>11</Dayvisited>
  </place>
</root>

此文件将包含随机名称,并将包含数百个地方。但到目前为止我可以将地方加载到网格,选择一个地方,细节进入文本框进行编辑,但我只能将其添加到列表中,而不只是更新所选地点或删除它

1 个答案:

答案 0 :(得分:1)

您最好利用DataBinding。这将完成所有繁重的工作,而无需自己编码。您只需要在数据集中读取和写入XML文件。

首先在项目中添加一个新项DataSet(在数据类别中找到),将其命名为Database。右键单击设计图面添加DataTable,选择Add&gt;数据表。为您的DataTable 地点命名。接下来在表格中添加4列Name,Location,Info和Dayvisited 在数据集的属性中,清空字段命名空间 当你完成后,这将是你的结果:

dataset

构建项目。

在设计模式下打开Winform 从工具箱中拖出类别数据组件BindingSource,BindingNavigator,DataGridView和DataSet。

对于DataSource,选择您在上一步中创建的Typed数据集database

单击bindingSource并将属性DataSource设置为 database 。将DataMember设置为 place

单击bindingnavigator。将属性Bindingsource设置为 binsdingSource1 (假设您未使用其默认名称)。

单击datagridview。将属性DataSource设置为 bindingSource1

为每个字段添加文本框。对于属性中的每个文本框,打开DataBindings类别,对于Text属性,选择 bindingSource1 - &gt;名称(重复其他属性)。

在表单中添加一个按钮以加载数据集。这是其点击事件中的代码:

database2.ReadXml("Database.xml");
this.button2.Enabled = true;
button1.Enabled = false;

在表单中添加一个按钮以保存数据集。这是其点击事件中的代码:

database2.WriteXml("Database.xml");

如果你完成所有这些就是你的项目应该是什么样子:

project overview

当您运行它并单击加载按钮时,选择记录,使用导航器添加新记录并单击保存,这将是您的结果:

example