0

我的网页由具有插入/更新/删除功能的 GridView 控件组成;它的数据存储在一个 XML 文件中。面临的问题是,当我插入新行时,子节点(新插入的日期)在复制到 xml 文件时出现在其子节点(** pos 节点)之外:例如:

<root>
  <pos>
    <partNumbers>
      <partid>0</partid>
      <partnumber>796547</partnumber>
    </partNumbers>
    <partNumbers>
      <partid>3</partid>
      <partnumber>567890</partnumber>
    </partNumbers>
  </pos>
  <partNumbers>
    <partid>10</partid>
    <partnumber>129123</partnumber>
  </partNumbers>
</root>

...我的目标是让新插入的行保留在节点如下图:

<root>
      <pos>
        <partNumbers>
          <partid>0</partid>
          <partnumber>796547</partnumber>
        </partNumbers>
        <partNumbers>
          <partid>3</partid>
          <partnumber>567890</partnumber>
        </partNumbers>
         <partNumbers>
        <partid>10</partid>
        <partnumber>129123</partnumber>
      </partNumbers>
      </pos>
     </root>

以下是我的插入代码:

protected void gvPartNumber_RowCommand(object sender, GridViewCommandEventArgs e)
    {

        if (e.CommandName == "insertXMLData")
        {
            string partid = ((TextBox)gvPartNumber.FooterRow.FindControl("txtPartIDInsert")).Text;
            string partnumber = ((TextBox)gvPartNumber.FooterRow.FindControl("txtPartNumberInsert")).Text;
            BindGridView();
            DataTable dtXMLInsert = (DataTable)gvPartNumber.DataSource;

            DataSet dsgvPartNumber = new DataSet();
            dsgvPartNumber.ReadXml(Server.MapPath("~/xml/storeUserInfo.xml"));
            DataRow drInsert = dsgvPartNumber.Tables["partNumbers"].NewRow();
            drInsert["partid"] = partid;
            drInsert["partnumber"] = partnumber;
            dsgvPartNumber.Tables["partNumbers"].Rows.Add(drInsert);
            dsgvPartNumber.WriteXml(Server.MapPath("~/xml/storeUserInfo.xml"));
            BindGridView();

        }
      }

我可以请我就我在这里做错了什么得到一些指导吗?

4

1 回答 1

0

尚未对此进行测试,但基于它在根目录下添加 XML 的事实,我猜想以下行需要更改:

dsgvPartNumber.Tables["partNumbers"].Rows.Add(drInsert);

dsgvPartNumber.Tables["pos"].Rows.Add(drInsert);

编辑:

开始了:

添加:

DataRow drParent = dsgvPartNumber.Tables["pos"].Rows[0];
drInsert.SetParentRow(drParent);

最终代码应为:

DataSet dsgvPartNumber = new DataSet();
dsgvPartNumber.ReadXml(Server.MapPath("~/xml/storeUserInfo.xml"));
DataRow drInsert = dsgvPartNumber.Tables["partNumbers"].NewRow();
drInsert["partid"] = partid;
drInsert["partnumber"] = partnumber;
DataRow drParent = dsgvPartNumber.Tables["pos"].Rows[0];
drInsert.SetParentRow(drParent);
dsgvPartNumber.Tables["partNumbers"].Rows.Add(drInsert);
dsgvPartNumber.WriteXml(Server.MapPath("~/xml/storeUserInfo.xml"));
BindGridView();
于 2013-08-08T15:01:56.983 回答