Reputation: 608
I've got TreeView
that contains nodes and after clicking on one of them, data is loading from file and fills TextBoxes
etc. I want to prevent creating duplicates, so everytime textBox "title" contains entry that already exist in .xml file, it gets deleted.
My problem is that after first click on the button that adds entry everything is ok. But after second click (textBox.Text
value is unchanged, so it'll be a duplicate) node disappears, even if I modify it. And after every double click new child node in treeView is added. I tried to do it by myself, but I ran out of ideas.
button code:
private void button1_Click(object sender, EventArgs e)
{
XDocument doc = XDocument.Load("test.xml");
bool ifDuplicate = doc.Descendants("dog")
.Any(x => (string)x.Attribute("name") == textBox1.Text);
if (ifDuplicate == true)
{
var xElement = (from q in doc.Elements("dogs").Elements("dog")
where q.Attribute("name").Value == textBox1.Text
select q);
foreach (var a in xElement)
a.Remove();
doc.Save("test.xml");
return;
}
gender(); //determines in which root node this entry will appear as child node; just comboBox with few exceptions
TreeViewOperations.SaveTree(treeView1, "test2.xml"); //saving treeView1
Save("test.xml"); //saving file that contains data form textBoxes etc.
statusBarUpdate();
}
So my question is: is there any better way to modify existing nodes and deleting duplicates? Can also attach Load method if needed.
edit: Save method
private void Save(string filename) { XDocument database = XDocument.Load(filename); XElement dog = new XElement("dog"); database.Element("dogs").Add(dog); dog.Add(new XAttribute("name", textBox1.Text)); dog.Add(new XElement("breed", comboBox3.Text)); dog.Add(new XElement("sex", radioButton3.Checked)); database.Save(filename); }
Upvotes: 0
Views: 549
Reputation: 13022
I think your problem comes from the return
in the if (ifDuplicate)
block, as it prevent the method to add the new item.
Here is the solution I would use:
private void button1_Click(object sender, EventArgs e)
{
XDocument doc = XDocument.Load("test.xml");
// Removes all existing elements
foreach (XElement xElement in from q in doc.Elements("dogs").Elements("dog")
where q.Attribute("name").Value == textBox1.Text
select q)
xElement.Remove();
gender(); //determines in which root node this entry will appear as child node; just comboBox with few exceptions
TreeViewOperations.SaveTree(treeView1, "test2.xml"); //saving treeView1
Save("test.xml"); //saving file that contains data form textBoxes etc.
statusBarUpdate();
}
Upvotes: 1