Delete node from treeView when Attribute are similar - c#

Am working on my first C# Winform application :(
I browse an XML file to a treeView , then I select node and I wante do delete it.My problem is :
Each node contains an Id attribute , then this node is used two or tree time in the same file , ans i want to delete all the duplicate .
This is an exp :
<list>
<object number="3" background_colour="7" id="2996" name="MyFirst" type="2">
<child id="3794" x="0" y="0"/>
<child id="13794" x="0" y="44"/>
<child **id="13794**" x="239" y="44"/>
</object>
<object height="4" id="13793" line="24487" direction="1"/>
<object height="194" **id="13794"** line_attributes="24487" line ="0"/>
</list`>
So, Now I can delete node ( node is an object) , but I want if i delete the object with id =13794 , I automaticlly delete also the Child with id =13794
I really think about this from one week :( if someone have an idea . Thanks.
My function Code :
private void DeleteHandler(TreeNode tNode)
{
tNode.BackColor = Color.Red;
var messageResult = MessageBox.Show("Are u sur to delete node and childs?", "Alerte de suppression", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (messageResult == System.Windows.Forms.DialogResult.Yes)
RemoveChildNodes(tNode);
else
tNode.BackColor = Color.Transparent;
}
private void RemoveChildNodes(TreeNode aNode)
{
if (aNode.Nodes.Count > 0)
{
for (int i = aNode.Nodes.Count - 1; i >= 0; i--)
{
aNode.Nodes[i].Remove();
}
}
var messageResult = MessageBox.Show("Delete from XML too ?", "Alerte de suppression", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (messageResult == System.Windows.Forms.DialogResult.Yes)
aNode.Remove();
}
private void deleteNode_Click(object sender, EventArgs e)
{
TreeNode sourceNode = sourceTreeView.SelectedNode;
DeleteHandler(sourceNode);
}

Using LINQ you could delete all nodes in the XML with a certain ID like this.
private XDocument DeleteID(string XmlFile, string NodeID)
{
XDocument list = XDocument.Load(XmlFile);
list.Descendants().Where(elm => (string)elm.Attribute("id") == NodeID).Remove();
return list;
}
You could then edit RemoveChildNodes to be something like:
private void RemoveChildNodes(TreeNode aNode)
{
//get the id from the node (I don't know where id is for our purpose I'll say it is in tag
XDocument list = DeleteID(#"c:\temp\test.xml", (string)aNode.Tag);
//reload the tree here
var messageResult = MessageBox.Show("Delete from XML too ?", "Alerte de suppression", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (messageResult == System.Windows.Forms.DialogResult.Yes)
{
list.Save(#"c:\temp\test.xml");
}
}

If I understand what you want to do is remove all the nodes from you Tree that have the same ID. LINQ can be used to build a collection of all Nodes that have a particular ID and then you can just remove all the nodes in the list.
Sorry I haven't time at the moment to produce any code at the moment but I hope this helps.
Ok I have added some code.
Here is a quick piece of code I knocked up. Use it for an idea, I have not tested it. This will only check the top level of nodes but it wouldn't be hard to correct this.
IEnumerable<TreeNode> Result = TreeView.Nodes.WHERE((N) => N.ID == "13794");
foreach(TreeNode Node in Result){TreeView.Nodes.Remove(Node);}
Hope this helps
Danny

Related

XMLNode. HasChild considers InnerText as a child node

I’m working on a windows form application I’m trying to see if a certain xml node has child nodes, in the first lines of my code I used OpenFileDialog to open an xml file; in this case the xml sample below.
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
</bookstore>
In my windows form application, I have an open button and a textbox1, the textbox1 is only used to display the address of the xml file and the open button sets everything in motion. Somewhere in the code I have the following lines of code:
using System;
using System.Data;
using System.Windows.Forms;
using System.Xml;
using System.IO;
//other lines of code
private void Open_XML_button_Click(object sender, EventArgs e)
{
//other lines of code
XmlDocument xmldoc = new XmlDocument();
string XML_Location;
XML_Location = textBox1.Text;
xmldoc.Load(XML_Location);
string category = "category = 'cooking'";
XmlNode test1 = xmldoc.SelectSingleNode(string.Format("/bookstore/book[#{0}]/author", category));
if (test1.HasChildNodes == true)
{
MessageBox.Show("It has Child nodes");
}
else
{
MessageBox.Show("it does not have Child nodes");
}
}
Here is what I don’t understand, I’m pointing to the author node which, as far as I can tell, does not have a child node but my code states that it does; if I were to erased Giada de Laurentiis then my code would say that the author node does not have
What Am I doing wrong?
You could check whether there are any child nodes that don't have a NodeType of XmlNodeType.Text:
string category = "category = 'cooking'";
XmlNode test1 = xmldoc.SelectSingleNode(string.Format("/bookstore/book[#{0}]/author", category));
if (test1.ChildNodes.OfType<XmlNode>().Any(x => x.NodeType != XmlNodeType.Text))
{
MessageBox.Show("It has Child nodes");
}
else
{
MessageBox.Show("it does not have Child nodes");
}
It has a child node which is an instance of https://msdn.microsoft.com/en-us/library/system.xml.xmltext(v=vs.110).aspx XmlText. In the DOM there are different kind of nodes and the property HasChildNodes checks for any kind of child nodes (element, comment, processing instruction, text, cdata).

how to assign image for Parent node and child nodes in treeview from assigned imagelist in c#?

I have a TreeView and an associated ImageList. What are the steps to add images to the Parent and child nodes ?
All the nodes are being added from the code. Nothing is done from the Design.
public void fill_tree()
{
host_listbox_new.Items.Clear();
foreach (KeyValuePair<string, host_config> hlitem in host_list)
{
string sitem = hlitem.Key;
if (host_list[sitem].sessionOptions == null)
host_list[sitem].sessionOptions = new SessionOptions();
host_list[sitem].sessionOptions.Protocol = Protocol.Sftp;
host_list[sitem].sessionOptions.HostName = host_list[sitem].ip;
host_list[sitem].sessionOptions.UserName = host_list[sitem].username;
host_list[sitem].sessionOptions.Password = host_list[sitem].password;
host_list[sitem].sessionOptions.PortNumber = Convert.ToInt32(host_list[sitem].port);
//host_list[sitem].sessionOptions.SshHostKeyFingerprint = host_list[sitem].rsa;
if (treeView1.SelectedNode != null)
{
treeView1.SelectedNode.Nodes.Add(hlitem.Key.ToString());
}
else
{
treeView1.Nodes[0].Nodes.Add(hlitem.Key.ToString());
}
}
}
private void Parent_Load(object sender, EventArgs e)
{
read_process_config();
read_host_config();
host_listbox.Items.Clear();
treeView1.BeginUpdate();
treeView1.Nodes.Add("Servers");
fill_tree();
treeView1.EndUpdate();
treeView1.ExpandAll();
connect_server_bttn.Enabled = false;
}
i want to add items i.e child nodes to Server Parent node each of them having one image before them ( green image if hlitem.Value.connected is true. red image if hlitem.Value.connected is false)
But i have no idea about treeview or imagelist.
Can anyone help me about the whole thing?
The Add command returns a reference to the new Node. You can use it to style the Node.
Change your code to this:
if (treeView1.SelectedNode != null)
{
TreeNode tn =treeView1.SelectedNode.Nodes.Add(hlitem.Key.ToString());
tn.ImageIndex = yourIndex;
}
else
{
TreeNode tn =treeView1.Nodes[0].Nodes.Add(hlitem.Key.ToString());
tn.ImageIndex = yourIndex;
}
Or whatever logic you need to set the index.
If you need the parent node's index you could write:
tn.ImageIndex = tn.Parent.ImageIndex;
You may also want ot check out the other formats of the Add method. Some let you include the ImageIndex directly. You can also include the SelectedIndex; especially if you don't want that you should include it to prevent the Tree using its default SelectedIndex!
This will set the node to show the 2nd image, whether selected or not:
TreeNode tn =treeView1.Nodes[0].Nodes.Add(sitem, sitem, 1,1 );
Since you can't set a property of an object before you have created it, you can't set the Child nodes when you create the parent node. Instead you can use a simple function to do the changes:
void copyImgIndexToChildren(TreeNode tn)
{
if (tn.Nodes.Count > 0)
foreach (TreeNode cn in tn.Nodes) cn.ImageIndex = tn.ImageIndex;
}
void copyImgIndexToAllChildren(TreeNode tn)
{
if (tn.Nodes.Count > 0)
foreach (TreeNode cn in tn.Nodes)
{
cn.ImageIndex = tn.ImageIndex;
copyImgIndexToAllChildren(cn);
}
}
The first method changes the direct ChildNodes only , the 2nd recursively changes all levels below the starting node.
BTW: Is there a reason to use hlitem.Key.ToString() in your code instead of sitem?

How to compare previous selected node with current selected node on asp.net treeview

I want to compare last selected node and current selected node on the treeview by using java script.
Please suggest me with some code samples to compare last selection and current selection node on the treeview.
If both the node selections are same , we need to deselect the same node.
Thanks. Please help on this.
I have resolved by server side code:
protected void TreeView1_PreRender(object sender, EventArgs e)
{
if (TreeView1.SelectedNode != null)
{
if (!string.IsNullOrEmpty(ADUtility.treenodevalue))
{
if (ADUtility.treenodevalue == TreeView1.SelectedNode.ValuePath)
{
TreeView1.SelectedNode.Selected = false;
}
else
{
ADUtility.treenodevalue = TreeView1.SelectedNode.ValuePath;
}
}
else
{
ADUtility.treenodevalue = TreeView1.SelectedNode.ValuePath;
}
}
}
I am just giving you the Pseudo code for this after that you can implement it by own.
Make 2 Global variables CurrentselectedNode and PreviousselectedNode
And make a ArrayList of Nodes
Arraylist<Object> nodeCollection;
var PreviousselectedNode;
var CurrentselectedNode;
if(nodeCollection.Current != null)
{
PreviousselectedNode= nodeCollection.Current;
var tempselectedItem = Products_Data.selectedNodeID.value;
var CurrentselectedNode = Document.getElementById(tempselectedItem);
// Here Do what you want to do with current Node and Previous Node
nodeCollection.Add(tempselectedNode);
}
else
{
var tempselectedItem = Products_Data.selectedNodeID.value;
var tempselectedNode = Document.getElementById(tempselectedItem);
nodeCollection.Add(tempselectedNode);
}

How to insert data into an existing xml file in asp.net?

I'm using Visual Web Developer 2008 Express Edition and I need your assistance since I'm new to it. I'm trying to insert or write a data to my xml file so that I can display it into my xml control. Now, what I'm trying to do here is everytime the user enter a message into the textbox he has an option to save it so if he clicks the command button I want to save the text message from the textbox into any elements of my xml file. Let say, I want to insert it in the element of my xml file. How do I do it using C# or VB.Net codes? I have my xml file below and my C# code but the c# code doesn't work for me. I need the code for that either in c# or vb.net, either way will work for me.
Thank you very much and I greatly appreciate any help that could be shared.
myxmlfile.xml
<?xml version="1.0" encoding="utf-8" ?>
<comments>
<comment>
Your Comments Here: Please post your comments now. Thank you.
</comment>
<comment2>
Note: Please do not post any profane languages.
</comment2>
<comment3>
I don't like their service. It's too lousy.
</comment3>
<comment4>
Always be alert on your duty. Don't be tardy enough to waste your time.
</comment4>
</comments>
code
protected void Button1_Click(object sender, EventArgs e)
{
System.Xml.Linq.XDocument mydoc =
new System.Xml.Linq.XDocument(
new System.Xml.Linq.XDeclaration("1.0", "UTF-8", "yes"),
new System.Xml.Linq.XElement("comment",
new System.Xml.Linq.XComment(TextBox1.Text)));
mydoc.Save("myxmlfile.xml",System.Xml.Linq.SaveOptions .None);
}
#Joseph LeBrech and #AVD --Thank you very much for your reply. That code would add a new root element in myxmlfile so the problem is that the new root element is not showing on my xml control when the page is reloaded because the new root element is not included on my xslt file to show the myxmlfile on the xml control. I don't want to add a new root element on myxmlfile. I just want to insert the messages entered from the textbox into the existing element of myxmlfile which is the element so that it can be shown on the xml control where i intend to display the myxmlfile. I hope you can modify the code for me again. Thank you very for your help. I greatly appreciated it.
You have to specify the absolute file path using MapPath() to save the XML document and don't increment tag name like comment1,comment2.. etc.
Take a look at code-snippet:
protected void Button1_Click(object sender, EventArgs e)
{
string file = MapPath("~/comments.xml");
XDocument doc;
//Verify whether a file is exists or not
if (!System.IO.File.Exists(file))
{
doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"),
new System.Xml.Linq.XElement("comments"));
}
else
{
doc = XDocument.Load(file);
}
XElement ele = new XElement("comment",TextBox1.Text);
doc.Root.Add(ele);
doc.Save(file);
}
EDIT: If you want to insert <comment> tag into existing xml document then no need to create XDocument. Just load the existing document and add a new element at the root.
protected void Button1_Click(object sender, EventArgs e)
{
string file = MapPath("~/myxmlfile.xml");
XDocument doc = XDocument.Load(file);
XElement ele = new XElement("comment",TextBox1.Text);
doc.Root.Add(ele);
doc.Save(file);
}
To add another <comment> tag inside <comment>:
XElement ele = new XElement("comment",TextBox1.Text);
doc.Root.Element("comment").Add(ele);
doc.Save(file);
To replace the text value of <comment> tag:
doc.Root.Element("comment").Value = TextBox1.Text;
//doc.Root.Element("comment").Value += TextBox1.Text; //append text
doc.Save(file);
XML document :
<?xml version="1.0" encoding="utf-8" ?>
<comments> <!-- Root Node -->
<comment>First Child</comment>
<comment> <!-- Second Child -->
<comment>Nested</comment>
</comment>
</comments>
myDoc.Element("comments").Add(new xElement("comment5") { Value = "put the value in here"});
Design the page like this.In button click event write the following
code
protected void btnInsert_Click(object sender, EventArgs e)
{
System.Xml.XmlDocument myXml = new System.Xml.XmlDocument();
myXml.Load(Server.MapPath("InsertData.xml"));
System.Xml.XmlNode xmlNode = myXml.DocumentElement.FirstChild;
System.Xml.XmlElement xmlElement = myXml.CreateElement("entry");
xmlElement.SetAttribute("Name", Server.HtmlEncode(txtname.Text));
xmlElement.SetAttribute("Location", Server.HtmlEncode(txtlocation.Text));
xmlElement.SetAttribute("Email", Server.HtmlEncode(txtemail.Text));
xmlElement.SetAttribute("Gender", Server.HtmlEncode(ddlgender.SelectedItem.Text));
myXml.DocumentElement.InsertBefore(xmlElement,xmlNode);
myXml.Save(Server.MapPath("InsertData.xml"));
BindData();
lbldisplay.Text = "Record inserted into XML file successfully";
txtname.Text = "";
txtlocation.Text = "";
txtemail.Text = "";
}
private void BindData()
{
XmlTextReader xmlReader = new XmlTextReader(Server.MapPath("InsertData.xml"));
xmlReader.Close();
}
and also put events tag in xml file.
Now run the application and check the output

textbox value to be stored into a new node in xml file

i have a textbox for users to enter their new email address. they will click the "Update" button and this text that they entered will then create a new entry in an existing XML file. this xml file is used to populate 2 dropdownlist and needs to constantly update the dropdownlist with new updated entries that user entered.
i tried the following code snipper but i am weak at methods.. so please guide me
xml file: (eg i want a new builder entry)
<?xml version="1.0" encoding="utf-8"?>
<email>
<builderemail>
<builder>
<id>1</id>
<value>builder#xyz.com</value>
</builder>
<builder>
<id>2</id>
<value>Others</value>
</builder>
</builderemail>
<manageremail>
<manager>
<id>1</id>
<value>manager#xyz.com</value>
</manager>
<manager>
<id>2</id>
<value>Others</value>
</manager>
</manageremail>
</email>
so upon this button click i call the method AddNodeToXMLFile
protected void Button1_Click(object sender, EventArgs e)
{
AddNodeToXMLFile("~/App_Data/builderemail.xml", email);
}
public void AddNodeToXMLFile(string XmlFilePath, string NodeNameToAddTo)
{
//create new instance of XmlDocument
XmlDocument doc = new XmlDocument();
//load from file
doc.Load(XmlFilePath);
//create main node
XmlNode node = doc.CreateNode(XmlNodeType.Element, "builder", null);
//create the nodes first child
XmlNode ButtonName = doc.CreateElement("id");
//set the value
ButtonName.InnerText = "1";
//create the nodes second child
XmlNode url = doc.CreateElement("value");
//set the value
url.InnerText = "" + TextBox1.Text;
// add childes to father
node.AppendChild(id);
node.AppendChild(value);
// find the node we want to add the new node to
XmlNodeList l = doc.GetElementsByTagName(NodeNameToAddTo);
// append the new node
l[0].AppendChild(node);
// save the file
doc.Save(XmlFilePath);
}
i think there is something wrong with my code..many thanks for your help
You should write:
// add children to father
node.AppendChild(ButtonName);
node.AppendChild(url);
and you should check if your xmlnodelist contains any nodes to prevent exceptions:
if (l.Count > 0)
{
// append the new node
l[0].AppendChild(node);
}
For the rest it looks alright to me. Good luck!

Categories

Resources