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.
Related
Im currently trying to get drag/drop within a treeview working(using databinding and HierarchicalDataTemplate), and have the dragging working, but im running into a problem when trying to get the drop working, since i need to get the data item being dropped on and add it to its item collection of children nodes.
//treeitem is the name of my item data class
private void TreeViewItem_Drop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent("DragableTreeViewItem"))
{
//the data of the treeitem i need to duplicate, provided by the drag operation
TreeItem data = e.Data.GetData("DragableTreeViewItem") as TreeItem;
TreeViewItem tvi = sender as TreeViewItem;
//here im getting the treeviewitem, but i need the treeitem
}
}
My best idea on how to get around this was to assign the treeitem as the tag of the treeviewitem on initialization/loading of the tree, and to do so i need to get the itemcontainer of the item, which i already have a working function to get that which i use when initiating the DoDrag()
//returns the item container of the parent of the TreeItem given
private TreeViewItem GetParentContainerFromItem(TreeItem ti)
{
List<TreeItem> GetOrderedParents(TreeItem item)
{
TreeItem currentParent = item;
List<TreeItem> items = new List<TreeItem>();
int i = 0;
do
{
if (currentParent.parentItem != null)
{
items.Insert(0, currentParent);
currentParent = currentParent.parentItem;
}
else
{
items.Insert(0, currentParent);
i++;
return items;
}
} while (i == 0);
return null;
}
//the local tree in a list, ordered from the original item (in this case "ti") at 0, down to the root at the end of the list
List<TreeItem> LocalHierarchy = GetOrderedParents(ti);
if (LocalHierarchy != null)
{
//print out the names of each treeitem in it, in order from the root down
string hierarchyString = "";
foreach (TreeItem t in LocalHierarchy)
{
if (hierarchyString == "")
{
hierarchyString = t.Title;
}
else
{
hierarchyString = (hierarchyString + ", " + t.Title);
}
}
System.Console.WriteLine(hierarchyString);
TreeViewItem localCurrentParent = null;
TreeViewItem finalContainer = null;
//walk down the tree in order to get the container of the parent
foreach (TreeItem t in LocalHierarchy)
{
//if the parent of the item given is a root node, meaning we can return its container
if (LocalHierarchy.IndexOf(t) == 0 && (LocalHierarchy.IndexOf(t) == (LocalHierarchy.Count - 2)))
{
finalContainer = treeView.ItemContainerGenerator.ContainerFromItem(t) as TreeViewItem;
break;
}
else
//if we're at a root node
if (LocalHierarchy.IndexOf(t) == 0)
{
localCurrentParent = treeView.ItemContainerGenerator.ContainerFromItem(t) as TreeViewItem;
}
else
//if we're at the 2nd to last, AKA the parent of the item given
if (LocalHierarchy.IndexOf(t) == (LocalHierarchy.Count - 2))
{
finalContainer = localCurrentParent.ItemContainerGenerator.ContainerFromItem(t) as TreeViewItem;
break;
}
else
{
localCurrentParent = localCurrentParent.ItemContainerGenerator.ContainerFromItem(t) as TreeViewItem;
}
}
if (finalContainer == null)
{
System.Console.WriteLine("Final container is null");
}
return finalContainer;
}
else
{
System.Console.WriteLine("ERROR: LocalHierarchy is null");
return null;
}
}
This seems to work perfectly when using to start the DoDrag()
private void DoDrag()
{
if(selectedItem != null)
{
TreeItem t = selectedItem;
TreeViewItem tvi = null;
if (t.parentItem == null)
{
//it has no parent, and is a root node
tvi = treeView.ItemContainerGenerator.ContainerFromItem(t) as TreeViewItem;
}
else
{
//it has a parent, and i can get the container for the parent
tvi = GetParentContainerFromItem(t).ItemContainerGenerator.ContainerFromItem(t) as TreeViewItem;
}
DragDrop.DoDragDrop(tvi, new DataObject("DragableTreeViewItem", t, true), DragDropEffects.Copy);
dragNeeded = false;
}
else if(selectedItem == null)
{
Console.WriteLine("Selected item was null; cant drag");
}
}
But when i try to use it in my function to assign container tags it says that Container was null and that GetParentContainerFromItem returned null, yet my function does not log that it returned null
private void AssignContainerTag(TreeItem t)
{
TreeViewItem Container = null;
if (t.parentItem == null)
{
//its a root node
Container = treeView.ItemContainerGenerator.ContainerFromItem(t) as TreeViewItem;
Container.Tag = t;
}
else
{
//it is not a root node
Container = GetParentContainerFromItem(t).ItemContainerGenerator.ContainerFromItem(t) as TreeViewItem;
Container.Tag = t;
}
}
Ive spent days stumped on why this does not seem to work, so if someone could give me some pointers on what im doing wrong or another way i could get the item from its container it would be a lifesaver. Also please excuse if this is poorly written, i am exhausted and about to go to sleep.
Your question is a little bit confusing. But it looks like you are trying to get the data item of the TreeViewItem which is the drop target of the drag&drop operation.
This is pretty simple. All you need to know is that if the item container is auto-generated via data binding (ItemsControl.ItemsSource) the DataContext of the container is the data item itself.
This applies to all item containers of an ItemsControl (e.g., ComboBoxItem, ListBoxItem, ListViewItem).
So TreeViewItem.DataContext references the underlying TreeItem instance that is wrapped by the TreeViewItem:
private void TreeViewItem_Drop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent("DragableTreeViewItem"))
{
var sourceItem = e.Data.GetData("DragableTreeViewItem") as TreeItem;
var dropTargetItemContainer = sender as TreeViewItem;
var dropTargetItem = targetItemContainer.DataContext as TreeItem;
}
}
Remark
It looks like you are using the ItemContainerGenerator wrong. TreeView.ItemContainerGenerator will only handle top level items (i.e. child items). But as a tree node can have child nodes, each TreeViewItem is itself an ItemsControl as it contains an ItemsPresenter to display child items.
Therefore you have to use the appropriate ItemContainerGenerator to retrieve the child container or ItemContainerGenerator will return null.
For top-level items use TreeView.ItemContainerGenerator.
For child items use the parent's TreeViewItem.ItemContainerGenerator.
Also, in case of UI virtualization is enabled not all containers are generated when the TreeView is loaded. They are generated when need e.g., for display. Those containers (the TreeViewItem) are also shared to save resources. So once you set the TreeViewItem.Tag property its value might get lost as a new TreeViewItem instance is generated later to wrap the data item.
So you start at the root node and get its generated container. Now perform a tree search by traversing the TreeViewItems using a specific algorithm until you found the node where the DataContext equals the data item you are looking for and e.g., modify the Tag property.
You access the children of e.g. treeViewItemA by referencing the treeViewItemA.Items property and get their containers by calling treeVieItemA.ItemContainerGenerator.ContainerFromItem method for each child:
Example
public static class MyExtensions
{
// Get item container of item from TreeView, TreeViewItem, ListView or any ItemsControl
public static bool TryGetContainerOfChildItem<TItemContainer>(this ItemsControl itemsControl, object item, out TItemContainer itemContainer) where TItemContainer : DependencyObject
{
itemContainer = null;
foreach (object childItem in itemsControl.Items)
{
if (childItem == item)
{
itemContainer = (TItemContainer) itemsControl.ItemContainerGenerator.ContainerFromItem(item);
return true;
}
DependencyObject childItemContainer = itemsControl.ItemContainerGenerator.ContainerFromItem(childItem);
if (childItemContainer is ItemsControl childItemsControl && childItemsControl.TryGetContainerOfChildItem(item, out itemContainer))
{
return true;
}
}
return false;
}
}
Usage
// Search whole TreeView
if (treeView.TryGetContainerOfChildItem(item, out TreeViewItem itemContainer)
{
...
}
// Search from a specific parent TreeViewItem node
if (treeViewItem.TryGetContainerOfChildItem(item, out TreeViewItem itemContainer)
{
...
}
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 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);
}
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'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;
}
}
}