Deleting items from datagrid (xml)
I have a datagrid buttoncolumn which acts as delete buttons for my xml nodes. The elements are simply displayed in a boundcolumn, so there names get displayed.
Each item generated gets a unique id (each time one is made id+++). My question his how can i remove a item (the entire element node with that certain id) when i click on one of the buttons in the bound column?
<root>
<element id="0">
<name>One</name>
</element>
<element id="1">
<name>Two</name>
</element>
</root>
protected void dg_DeleteCommand(object sender, DataGridCommandEventArgs e)
{
XmlFunctions.Remove(index);
}/*dg_DeleteCommand*/
(function on other class, where all my xml methods are written)
public static void Remove(string index)
{
XmlDocument XMLDoc = ne开发者_如何学Gow XmlDocument();
XMLDoc.Load(XMLFile);
XPathNavigator nav = XMLDoc.CreateNavigator();
var node = nav.SelectSingleNode("/test/one[@id='" +???+ "']");
node.DeleteSelf();
XMLDoc.Save(XMLFile);
}
Edit: added datagrid
<asp:View ID="viewDelete" runat="server">
<asp:DataGrid ID="dgDelete runat="server" AutoGenerateColumns="False" OnDeleteCommand="dg_DeleteCommand">
<Columns>
<asp:BoundColumn DataField="name" HeaderText="names" />
<asp:ButtonColumn ButtonType="PushButton" Text="Delete" CommandName="Delete" ></asp:ButtonColumn>
</Columns>
</asp:DataGrid>
</asp:View>
protected void dg_DeleteCommand(object sender, DataGridCommandEventArgs e)
{
XmlFunctions.Remove(grid selected value);
}
public static void Remove(string itemValue)
{
XDocument doc = XDocument.Load("xmlfile.xml");
doc.Descendants("test")
.Where(p=>p.Attribute("id") != null
&& p.Attribute("id").Value == itemValue)
.SingleOrDefault().Remove();
}
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load("yourxmlfile.xml");
XmlNode xmlnode = xmldoc.DocumentElement.ChildNodes.Item(indice);
xmlnode.ParentNode.RemoveChild(xmlnode);
xmldoc.Save("yourxmlfile.xml");
I did this and it worked
精彩评论