单击删除按钮,从Datagridview中删除选定的行,并同时删除XML节点

时间:2019-12-02 17:56:35

标签: c# xml datagridview

目前,当用户突出显示整个行并选择“删除”按钮时,该代码从Datgridview中删除了该行,但未从XML文件中删除该行。因此,如果刷新页面,则以前删除的行仍将显示,因为网格视图从XML加载了尚未删除的数据。

这是XML的代码

    <?xml version="1.0" standalone="yes"?>
<NewDataSet>
  <Contacts>
    <FirstName>s</FirstName>
    <LastName>s</LastName>
    <Address>s</Address>
    <City>s</City>
    <Postcode>s</Postcode>
    <Number>s</Number>
  </Contacts>
  <Contacts>
    <FirstName>w</FirstName>
    <LastName>w</LastName>
    <Address>w</Address>
    <City>w</City>
    <Postcode>w</Postcode>
    <Number>w</Number>
  </Contacts>
  <Contacts>
    <FirstName>
    </FirstName>
    <LastName>
    </LastName>
    <Address>
    </Address>
    <City>
    </City>
    <Postcode>
    </Postcode>
    <Number>
    </Number>
  </Contacts>
  <Contacts>
    <FirstName>dkd</FirstName>
    <LastName>dkfskldf</LastName>
    <Address>asdfasf</Address>
    <City>dfs</City>
    <Postcode>dd</Postcode>
    <Number>dd</Number>
  </Contacts>
</NewDataSet>

这是删除按钮事件处理程序的代码

private void button2_Click(object sender, EventArgs e)
        {
            string Lname;

            DataGridViewSelectedRowCollection dgv_rc = this.dataGridView1.SelectedRows;

            foreach (DataGridViewRow dgv_r in dgv_rc)
            {
                this.dataGridView1.Rows.Remove(dgv_r);
            }

            if (dataGridView1.SelectedCells.Count > 0)
            {
                int selectedrowindex = dataGridView1.SelectedCells[0].RowIndex;
                DataGridViewRow selectedRow = dataGridView1.Rows[selectedrowindex];
                Lname = Convert.ToString(selectedRow.Cells["LastName"].Value);
                XmlDocument xdoc = new XmlDocument();
                xdoc.Load("Contacts.xml");
                foreach (XmlNode xNode in xdoc.SelectNodes("Contacts"))
                    if (xNode.SelectSingleNode("LastName").InnerText == Lname) xNode.ParentNode.RemoveChild(xNode);
                xdoc.Save("Contacts.xml");
                DialogResult dialog = MessageBox.Show(Lname + "deleted");
            }


        }

任何帮助将不胜感激

0 个答案:

没有答案