I have created a treeview with parent and childnodes created dynamically.Also have enabled checkbox property true.hence got check boxes for each node.
The problem is how to name these check boxes so that for a particular user if the value is true, the checkbox should be checked, else if the value is false the checkbox needs to be unchecked. true or false value is stored in a particular column in a db.
Please follow the code I've provided it might give you some Idea from what I understand from your question. I've provided the link as well.
http://msdn.microsoft.com/en-us/library/wwc698z7(v=vs.90).aspx
private void PrintRecursive(TreeNode treeNode)
{
// Print the node.
System.Diagnostics.Debug.WriteLine(treeNode.Text);
MessageBox.Show(treeNode.Text);
// Print each node recursively.
foreach (TreeNode tn in treeNode.Nodes)
{
PrintRecursive(tn);
}
}
// Call the procedure using the TreeView.
private void CallRecursive(TreeView treeView)
{
// Print each node recursively.
TreeNodeCollection nodes = treeView.Nodes;
foreach (TreeNode n in nodes)
{
PrintRecursive(n);
}
}
you can check which node is checked by the following code
foreach (TreeNode node in yourtreeview.Nodes)
{
if (node.Checked)
{ //here You can check here your parent nodes is checked or not
//your calculations
}
foreach (TreeNode ChildNode in node.Nodes)
{
if (ChildNode.Checked)
{ // here you can check your 2nd level nodes
}
foreach (TreeNode childofChild in ChildNode.Nodes)
{
if (childofChild.Checked)
{ here you can check your 3rd level node }
foreach (TreeNode GrandChildofChild in childofChild.Nodes)
{
if (GrandChildofChild.Checked)
{
//here you can check your fourth level node
}
}
}
}
}
Related
I have some nodes added to my TreeView (trvP). The root element has Tag property set to Root.
I'm trying to make it so if I check the root element, all other nodes will have the same status. However, executing the code below results in StackOverflowException.
private void trvP_AfterCheck(object sender, TreeViewEventArgs e)
{
if(e.Node.Tag.Equals("Root"))
{
var nodes = TreeViewExtensions.GetAllNodes(e.Node.TreeView);
foreach (TreeNode node in nodes)
node.Checked = e.Node.Checked;
}
}
The code for GetAllNodes function:
public static List<TreeNode> GetAllNodes(this TreeView _trv)
{
List<TreeNode> result = new List<TreeNode>();
foreach (TreeNode child in _trv.Nodes)
{
result.AddRange(child.GetAllNodes());
}
return result;
}
public static List<TreeNode> GetAllNodes(this TreeNode _trn)
{
List<TreeNode> result = new List<TreeNode>();
result.Add(_trn);
foreach (TreeNode child in _trn.Nodes)
{
result.AddRange(child.GetAllNodes());
}
return result;
}
It seems from debugging that it runs the var nodes = ... piece of code over and over, while only setting single node inside the foreach loop (the root node). However, nodes is a proper list of nodes with right values.
I can't see why this is executing over and over resulting in an exception.
Your GetAllNodes() extension for a TreeView starts with the first child node and calls the GetAllNodes() extension for this TreeNode.
This GetAllNodes() extension adds this very TreeNode to the result list.
So the first TreeNode in your list is your root node again.
This means in the line
node.Checked = e.Node.Checked;
you set the Checked property of your root node, which in turn calls the handler trvP_AfterCheck again for this root node. This now repeats infinitly, flooding your stack and raising the StackOverflowException.
To solve this, filter out the root node:
private void trvP_AfterCheck(object sender, TreeViewEventArgs e)
{
if(e.Node.Tag.Equals("Root"))
{
var nodes = e.Node.TreeView.GetAllNodes();
foreach (TreeNode node in nodes)
{
if (node == e.Node) continue; // don't do it for root again
node.Checked = e.Node.Checked;
}
}
}
Btw: the nice thing about extension methods is that you can call them syntactically as if they were instanc methods. So this
var nodes = TreeViewExtensions.GetAllNodes(e.Node.TreeView)
can simply be written as
var nodes = e.Node.TreeView.GetAllNodes();
you are calling GetAllNodes recursively which makes loop into infinite state..
try
public static List<TreeNode> GetAllNodes(this TreeView _trv)
{
List<TreeNode> result = new List<TreeNode>();
foreach (TreeNode child in _trv.Nodes)
{
result.Add(child);
}
return result;
}
when you are already looping to treenode into _trv.Nodes, you jst need to add current node into foreach statement..
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?
I have a treelist in my form with checkboxes enabled. I need to add anything checked to a list so I can write that list out. If I check any parent nodes (or highest level nodes) it includes them. If I select any parent nodes it also selects its children nodes (this is intentional), and displays those. But If I check any child nodes only, it won't add them to my list.
//check to see if there are any nodes checked
bool nodeHasCheck = false;
foreach (TreeNode n in nodes)
{
if (n.Checked)
{
nodeHasCheck = true;
break;
}
GetExtendedFeatures(n.Nodes);
}
//only return stuff if something's checked
if (nodeHasCheck == true)
{
foreach (TreeNode n in nodes)
{
if (n.Checked)
{
//n.BackColor = Color.Black;
nodeList.Add(n.Text);
}
GetExtendedFeatures(n.Nodes);
}
It also appears that if I select 2 parent nodes, the recursion that occurs (Think that's the right term) is causing it to find the first checked node, then starts over, and adds that same checked node a second time before it hits the second set of nodes.
I provided my node test, hopefully it's enough to identify why it's not detecting child nodes selected without the parent node selected.
UPDATED - 3/18/13
My button click code:
private void btnGenerate_Click(object sender, EventArgs e)
{
ScanNodes(treeView1.Nodes[0]);
}
private void ScanNodes(TreeNode parent)
{
foreach (TreeNode node in parent.Nodes)
{
if (node.Checked)
{
nodeList.Add(node.Text.ToString());
}
if (node.Nodes.Count > 0)
{
ScanNodes(node);
}
}
var message = string.Join(Environment.NewLine, nodeList);
message = message.Replace(Environment.NewLine, ", ");
MessageBox.Show(message);
nodeList.Clear();
}
To get a List of all the selected nodes in a TreeView you can use the following:
Supose the list is named nodeList:
//We First declare a recursive method to loop through all nodes,
//we need to pass a root node to start
private void ScanNodes(TreeNode parent)
{
foreach (TreeNode node in parent.Nodes)
{
if (node.Checked)
{
nodeList.Add(node.Text);
}
if (node.Nodes.Count > 0)
{
ScanNodes(node);
}
}
}
With that set up You just need to call the ScanNodes method and pass the root node of your TreeView:
ScanNodes(treeView1.Nodes[0]);
Regards,
I have an application with two forms. The first form is used to create TreeView nodes programmatically, and the second form has the actual TreeView. When the application loads I create two root nodes in the TreeView.
My problem is when I create my first sub-node for either of the root nodes, it is not highlighted. I give the Form and the TreeView focus, and also disabled the HideSelection property for the TreeView.
Once I add a another sub-node to either of the root nodes is when the inserted node becomes highlighted. I want each inserted node to be highlighted once it has been inserted, but that only works after the first one has been inserted.
Example Code:
m_ObjectAnimationForm.tr_vw_ANIMATION_OBJECT_LIST.SelectedNode = m_ObjectAnimationForm.tr_vw_ANIMATION_OBJECT_LIST.Nodes["OBJECTS_ROOT"].Nodes.Add(NewObject.ID, NewObject.ID);
I create a new tree node using the ID of the object for the 'KEY' and the string of the node, then that function returns the newly created tree node, making it the selected node in the tree.
After that code I call:
m_ObjectAnimationForm.tr_vw_ANIMATION_OBJECT_LIST.ExpandAll();
m_ObjectAnimationForm.tr_vw_ANIMATION_OBJECT_LIST.Focus();
I have a slightly different setup, in which I control the highlighted item in the TreeView, by way of selecting an item in a datagridview. It is not the most elegant methodology, but it works.
In Summary:
1.) Get Index from Source TreeView, Other Control, or elsewhere
2.) Expand all Nodes in Target TreeView
3.) Iterate through Tree Nodes in Target, until Index is Reached
4.) Set TreeView.SelectedNode = "the node that was found"
5.) Set Focus on TreeView
private void selectTreeViewItem(int dataGridViewRowIndex)
{
expandAllTreeViewNodes();
setTreeViewItem(dataGridViewRowIndex);
}
private void setTreeViewItem(int dataGridViewRowIndex)
{
int iterator = 0;
TreeNode tempNode = testStepTreeView.Nodes[iterator];
//don't need to actually return the integer...
iterator = findNode(tempNode, dataGridViewRowIndex, iterator);
testStepTreeView.Focus();
nodeFound = false;
}
private void expandAllTreeViewNodes()
{
if (testStepTreeView.Nodes.Count != 0)
{
foreach (TreeNode x in testStepTreeView.Nodes)
{
expandNode(x);
}
}
}
private void expandNode(TreeNode x)
{
if (x.IsExpanded == false)
{
x.Expand();
}
if (x.Nodes.Count > 0)
{
foreach (TreeNode y in x.Nodes)
{
expandNode(y);
}
}
}
private int findNode(TreeNode tempNode, int dataGridViewRowIndex, int iterator)
{
if (iterator > dataGridViewRowIndex)
{
return iterator;
}
if (iterator == dataGridViewRowIndex)
{
testStepTreeView.SelectedNode = tempNode;
nodeFound = true;
return iterator;
}
if (tempNode.Nodes.Count != 0)
{
iterator++;
if (iterator > dataGridViewRowIndex)
{
return iterator;
}
if (nodeFound == false)
{
iterator = findNode(tempNode.Nodes[0], dataGridViewRowIndex, iterator);
}
}
if (tempNode.NextNode != null)
{
iterator++;
if (iterator > dataGridViewRowIndex)
{
return iterator;
}
if (nodeFound == false)
{
iterator = findNode(tempNode.NextNode, dataGridViewRowIndex, iterator);
}
}
return iterator;
}
try using Node.Select(), it will select the node and highlight it too.
focus will not work here.
I've added checkboxes to my treeview, and am using the AfterSelect event (also tried AfterChecked).
My tree view is like this
1 State
1.1 City1
1.2 City2
1.3 City3
2 State
2.1 City1
2.2 City2
2.3 City3
etc.
I'm trying to run an event, so when a checkbox is clicked, the tag is added to an array ready for processing later. I also need to use it so if a state is clicked, it selects all the cities under that leaf.
treeSections.AfterSelect += node_AfterCheck;
private void node_AfterCheck(object sender, TreeViewEventArgs e)
{
MessageBox.Show("testing");
}
The above code works on the treeview if it has no heirarchy. But don't work on the treeview with the states and cities unless the text/label for each leaf is double clicked.
Any ideas?
I suggest using the combination of TreeView.NodeMouseClick and TreeView.KeyUp events... the click event will provide you the clicked node via event args and with the keyup you can use the currently selected node. Follow the example below...
//This is basic - you may need to modify logically to fit your needs
void ManageTreeChecked(TreeNode node)
{
foreach(TreeNode n in node.Nodes)
{
n.Checked = node.Checked;
}
}
private void convTreeView_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
ManageTreeChecked(e.Node);
}
private void convTreeView_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Space)
{
ManageTreeChecked(convTreeView.SelectedNode);
}
}
Using the node given each event you can now cycle through the Nodes collection on that node and modify it to be checked/unchecked given the status of the checked status of the node you acted upon.
You can even get fancy enough to uncheck a parent node when all child nodes are unchecked. If you desire a 3-state treenode (All Checked, Some Checked and None Checked) then you have to create it or find one that has been created.
Enjoy, best of luck.
Some code for you to consider :
Not considered here :
what to about which node is selected when checking, when a child node selection forces a parent node to be selected (because all other child nodes are selected).
could be other cases related to selection not considered here.
Assumptions :
you are in a TreeView with a single-node selection mode
only two levels of depth, as in OP's sample ("heavy duty" recursion not required)
everything done with the mouse only : extra actions like keyboard keypress not required.
if all child nodes are checked, parent node is auto-checked
unchecking any child node will uncheck a checked parent node
checking or unchecking the parent node will set all child nodes to the same check-state
...
// the current Node in AfterSelect
private TreeNode currentNode;
// flag to prevent recursion
private bool dontRecurse;
// boolean used in testing if all child nodes are checked
private bool isChecked;
private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
{
// prevent recursion here
if (dontRecurse) return;
// set the currentNode
currentNode = e.Node;
// for debugging
//Console.WriteLine("after check node = " + currentNode.Text);
// select or unselect the current node depending on checkstate
if (currentNode.Checked)
{
treeView1.SelectedNode = currentNode;
}
else
{
treeView1.SelectedNode = null;
}
if(currentNode.Nodes.Count > 0)
{
// node with children : make the child nodes
// checked state match the parents
foreach (TreeNode theNode in currentNode.Nodes)
{
theNode.Checked = currentNode.Checked;
}
}
else
{
// assume a child node is selected here
// i.e., we assume no root level nodes without children
if (!currentNode.Checked)
{
// the child node is unchecked : uncheck the parent node
dontRecurse = true;
currentNode.Parent.Checked = false;
dontRecurse = false;
}
else
{
// the child node is checked : check the parent node
// if all other siblings are checked
// check the parent node
dontRecurse = true;
isChecked = true;
foreach(TreeNode theNode in currentNode.Parent.Nodes)
{
if(theNode != currentNode)
{
if (!theNode.Checked) isChecked = false;
}
}
if (isChecked) currentNode.Parent.Checked = true;
dontRecurse = false;
}
}
}