Can't set TreeView.SelectedNode Property - c#

I'm trying to set the selected node after cleaning and refilling my treeview. Here's the code I tried:
private TreeNode selectednode;
private void ElementTextChanged(object sender, EventArgs e)//saves changes to the XElements displayed in the textboxes
{
BusinessLayer.ElementName = (sender as TextBox).Tag.ToString();
string Type = (sender as TextBox).Name;
string Value = (sender as TextBox).Text;
if (TView_.SelectedNode!=null)
{
selectednode = TView_.SelectedNode;
}
string NodePath = TView_.SelectedNode.FullPath.Replace("\\", "/");
Telementchange.Stop();
Telementchange.Interval = 2000;
Telementchange.Tick += (object _sender, EventArgs _e) => {
if (Type=="Value")
{
BusinessLayer.ChangeElementValue(NodePath,Value);//nembiztos hogy így kéne ezt meghívni
}
else
{
BusinessLayer.ChangeElementName(NodePath, Value);
BusinessLayer.ElementName = Value;
}
FillTree(BusinessLayer.Doc);
TView_.SelectedNode = selectednode; //nemműködikezaszar!!!!!
TView_.Select();
Telementchange.Stop();
};
Telementchange.Start();
}
For some season after I set the TView_.SelectedNode property it is null.
Thank you for helping!

Looking at the code you show you seem to do this:
store the currently selected Node in a variable
clean and refill the TreeView
select the stored Node
This is bound to fail as at the moment after the filling, the stored Node is no longer part of the TreeView's node collection unless you have added it again in the fill routine..
I don't think you do that.
If you want to re-select some node you will need to identify it in the new collection of nodes. If the Text is good enough for that do a recursive TreeView search like the one in L.B's answer here in this post (Not the accepted answer, though!)

I couldn't solve my problem by setting the SelectedNode property so i made a workaround.
private void RefreshTreeView()
{
FillTree(BusinessLayer.Doc);
TView_.SelectedNode = _selectednode;
ExpandToPath(TView_.TopNode, _selectedPath);
}
void ExpandToPath(TreeNode relativeRoot, string path)
{
char delimiter = '\\';
List<string> elements = path.Split(delimiter).ToList();
elements.RemoveAt(0);
relativeRoot.Expand();
if (elements.Count == 0)
{
TView_.SelectedNode = relativeRoot;
return;
}
foreach (TreeNode node in relativeRoot.Nodes)
{
if (node.Text == elements[0])
{
ExpandToPath(node, string.Join(delimiter.ToString(),elements));
}
}
}

Related

How to get item from item container in WPF?

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)
{
...
}

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 highlight the first inserted node in a tree view?

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.

Value of tag property disappears

I'm busy with a simple application. It reads xml and puts the information in a treeview.
I do this by creating TreeNodes and nest them, and finaly, return the root treenode. Because I want to show some extra information when a treenode is selected, I put the information in the tag property of the TreeNode. In this way, I should be able to retrieve the information when the node is selected.
But when I try to retrieve the information in the Tag property, it says the value = null.
Here is the code where I fill the tag. This is in a function which is recursively used to read the XML dom. treeNode is a paramater given to this function.
if (treeNode.Tag == null)
{
treeNode.Tag = new List<AttributePair>();
}
(treeNode.Tag as List<AttributePair>).Add(new AttributePair(currentNode.Name, currentNode.Value));
This is the event where a treenode is selected
private void tvXML_AfterSelect(object sender, TreeViewEventArgs e)
{
if (tvXML.SelectedNode.Tag != null)
{
}
if (e.Node.Tag != null)
{
}
}
Both values evaluate to null. How can I solve this problem?
The code you posted should work as-is. Something else in your code, code that you didn't post here, is causing this to break. It could be clearing the Tag, it could be a data binding set on the tag, etc.
Without seeing all your code, the best I can do is guess and help you isolate the problem.
Here's what I'd do: setup Visual Studio to allow stepping into the .NET framework source code with the debugger. Then, set a breakpoint on the setter for the TreeNode.Tag property. After you set the tag in your code to your AttributePair List, see when it gets set again. The breakpoint will hit, you'll look at the stack trace and see what exactly is clearing your Tag property.
If using Tag property isn't in principle, I'm recommend inherit TreeItem:
public class MyTreeNode : TreeNode
{
public List<AttributePair> list;
public MyTreeNode (string text,List<AttributePair> list) : base(text)
{
this.list = list;
}
//or
public MyTreeNode (string text) : base(text)
{
this.list = new List<AttributePair>();
}
}
And use it:
private void tvXML_AfterSelect(object sender, TreeViewEventArgs e)
{
if (tvXML.SelectedNode is MyTreeNode)
{
MyTreeNode selectedNode = tvXML.SelectedNode as MyTreeNode;
selectedNode.list.Add(.., ..);
}
if (e.Node is MyTreeNode)
{
MyTreeNode node = e.Node as MyTreeNode;
node.list.Add(.., ..);
}
}
Maybe you are assigning the values after Select event. Otherwise you can maintain a dictionary of TreeNode and tag values as workaround.
Try declaring/initialising your List object somewhere above (outside of the inner scope you are in) and when you assign to the .tag property - don't create a new list but rather assign previously created List object.
private TreeViewItem _subsender;
private object _senderTag;
public TreeViewItem _sender
{
get {
return _subsender;
}
set
{
_senderTag = value.Tag;
_subsender = value;
}
}
Got the same problem this the solution that i found
Just don't use the .tag but _senderTag
(don't change the lines in the set for some reason :D )
(You cant just reset the tag (maybe new TreeViewItem ))

Categories

Resources