Get certain rows of a treeView and fill another treeview - c#

How to get certain rows from TreeView with all sub rows and fill them into another treeView in c# syncfusion?
Thank you

If I've got your point and assuming that you are copying nodes from WindowsForms TreeViews the following code may helps :
private void Form1_Load(object sender, EventArgs e)
{
MoveNodes(treeView1,treeView2,1, 2);
}
void AddRootNode(TreeView tree, TreeNode node)
{
var newNode = new TreeNode(node.Text);
tree.Nodes.Add(newNode);
foreach (TreeNode child in node.Nodes)
AddChildNode(newNode, child);
}
void AddChildNode(TreeNode parent, TreeNode node)
{
var newNode = new TreeNode(node.Text);
parent.Nodes.Add(newNode);
foreach (TreeNode child in node.Nodes)
AddChildNode(newNode, child);
}
private void MoveNodes(TreeView source,TreeView destination, params int[] indexes)
{
foreach (var index in indexes)
{
if (index < 0 || index >= source.Nodes.Count)
continue;
AddRootNode(destination, source.Nodes[index]);
}
}

Related

asp.net treeview with folders and file from database

I have a requirement to bind folders and files to the treeview based on table data from data base, i tried lot of solution but failed to meet specific requirement.
Here is what im looking
Top folders
I have found one sample code and tried to achieve this
`
private void PopulateTreeview(DataTable dtFolders)
{
tvVendors.Nodes.Clear();
HierarchyTrees hierarchyTrees = new HierarchyTrees();
HierarchyTrees.HTree objHTree = null;
if (dtFolders.Rows.Count > 0)
{
foreach (DataRow dr in dtFolders.Rows)
{
objHTree = new HierarchyTrees.HTree();
objHTree.LevelDepth = int.Parse(dr["level"].ToString());
objHTree.NodeID = int.Parse(dr["folderid"].ToString());
objHTree.UnderParent = int.Parse(dr["parentid"].ToString());
objHTree.FIleName=dr["filename"].ToString();
objHTree.FilePath=dr["filepath"].ToString();
hierarchyTrees.Add(objHTree);
}
}
//Iterate through Collections.
foreach (HierarchyTrees.HTree hTree in hierarchyTrees)
{
//Filter the collection HierarchyTrees based on
//Iteration as per object Htree Parent ID
HierarchyTrees.HTree parentNode = hierarchyTrees.Find
(delegate(HierarchyTrees.HTree vendor)
{ return vendor.NodeID == hTree.UnderParent; });
//If parent node has child then populate the leaf node.
if (parentNode != null)
{
foreach (TreeNode tn in tvVendors.Nodes)
{
//If single child then match Node ID with Parent ID
if (tn.Value == parentNode.NodeID.ToString())
{
tn.ChildNodes.Add(new TreeNode
(hTree.NodeDescription.ToString(), hTree.NodeID.ToString()));
}
//If Node has multiple child ,
//recursively traverse through end child or leaf node.
if (tn.ChildNodes.Count > 0)
{
foreach (TreeNode ctn in tn.ChildNodes)
{
RecursiveChild(ctn, parentNode.NodeID.ToString(), hTree);
}
}
}
}
//Else add all Node at first level
else
{
tvVendors.Nodes.Add(new TreeNode
(hTree.NodeDescription, hTree.NodeID.ToString()));
}
}
tvVendors.ExpandAll();
}
public void RecursiveChild(TreeNode tn, string searchValue, HierarchyTrees.HTree hTree)
{
if (tn.Value == searchValue)
{
tn.ChildNodes.Add(new TreeNode
(hTree.NodeDescription.ToString(), hTree.NodeID.ToString()));
}
if (tn.ChildNodes.Count > 0)
{
foreach (TreeNode ctn in tn.ChildNodes)
{
RecursiveChild(ctn, searchValue, hTree);
}
}
}
Problem: I'm not able to bind file name to leaf node, if folder does not have any subfolder. bind the files. or if folder has subfolder and file both.bind both at same level. if folder is empty, it has nothing just bind it blank.
Could please test the code provide some solution`
foreach (TreeNode childnode in GetChildFolderNode(dataRow[ID].ToString(), table))
{
//Bind all folders
}
foreach (TreeNode childnode in GetChildFileNode(dataRow[ID].ToString(), table))
{
//bind all files
}

How to set position while traversing through Treeview

I want to traverse through a treeview & set the value property to be its position in the tree as shown below
A[val:1]->A1[val:11]
l l--->A2[val:12]
l----->A3[val:13]
B[val:2]->B1[val:21]
l l--->B2[val:22]
C[val:3]->C1[val:31]
l l--->C2[val:32]
I have written a recursive which returns me all the nodes but i am unable to assign the desired position to its nodes.
private void TraverseTreeNode(TreeNodeCollection nodes)
{
foreach (TreeNode node in nodes)
{
TraverseTreeNode(node.ChildNodes);
}
}
Considering that TreeNode.Value is of type string, this will, starting at level = 1:
private static void TraverseTreeNode(TreeNodeCollection nodes, int parentNumber)
{
var childNumber = 1;
foreach (TreeNode node in nodes)
{
node.Value = string.Format("{0}{1}", parentNumber, childNumber ).Substring(0,node.Depth+1);
TraverseTreeNode(node.ChildNodes, parentNumber);
childNumber++;
if (node.Depth == 0) { parentNumber++; }
}
}
Only works for two levels but is easily extendable by adding additional parameters to TraverseTreeNode.
UPDATE
The following will work for any depth in hierarchy:
private static void TraverseTreeNode(TreeNodeCollection nodes, int parentNumber)
{
var childNumber = 1;
foreach (TreeNode node in nodes)
{
node.Value = node.Parent != null && node.Parent.Value != null
? string.Format("{0}{1}", node.Parent.Value, childNumber)
: string.Format("{0}{1}", parentNumber, childNumber).Substring(0, node.Depth + 1);
TraverseTreeNode(node.ChildNodes, parentNumber);
childNumber++;
if (node.Depth == 0) { parentNumber++; }
}
}
As you need recursive method, try this
private void Caller()
{
TraverseTreeNode(treeView1.Nodes);
}
private void TraverseTreeNode(TreeNodeCollection nodes)
{
int index = 1;
foreach (TreeNode node in nodes)
{
node.Text = (node.Parent != null ? node.Parent.Text : string.Empty) + index++;
TraverseTreeNode(node.Nodes);
}
}

adding a child node to specific node in c#

I have a problem adding a childnode to specific node. Here is my code:
Method for painting tree
public void paint()
{
treeView1.Nodes.Clear();
TreeNode root = new TreeNode("Katalogas");
root.Name = "root";
treeView1.Nodes.Add(root);
foreach (string or in categories)
{
TreeNode subcat = new TreeNode(or);
subcat.Name = or;
root.Nodes.Add(subcat);
}
foreach (Preke or in PrekiuListas)
{
TreeNode subcat = new TreeNode(or.name);
subcat.Name = or.name;
TreeNode temp = FindNode(or.category);
temp.Nodes.Add(subcat);
}
Method for finding node
private TreeNode FindNode(String name)
{
foreach (TreeNode node in treeView1.Nodes[0].Nodes)
{
if (node.Nodes.Count > 0)
return FindNode(name);
if (node.Name == name)
return node;
}
return null;
}
I can add one child node to both nodes, but when i try to add another, i get stack overflow exception.. Please help, thanks
You have to pass the root node along with the method:
private TreeNode FindNode(String name, TreeNode root)
{
if(root.Name == name) return root;
Stack<TreeNode> nodes = new Stack<TreeNode>();
nodes.Push(root);
while(nodes.Count > 0)
{
var node = nodes.Pop();
foreach(TreeNode n in node.Nodes){
if (n.Name == name) return n;
nodes.Push(n);
}
}
return null;
}
//Usage
var node = FindNode(someName, treeView1.Nodes[0]);
//if your treeView has more root nodes, you have to loop through them
TreeNode node = null;
foreach(TreeNode node in treeView1.Nodes){
node = FindNode(someName, node);
if(node != null) break;
}
If the problem is just that of finding the node name, you can use the built-in TreeNodeCollection.Find() method for better performance:
public TreeNode[] Find(string key, bool searchAllChildren);
Example:
n.Nodes.Find("name", true);
The second parameter indicates that you want to search in all nodes recursively.
Also, this returns an entire TreeNode[] array, not a single node. So, you have to loop in them to fill or take the node[0] element if yo want to use just the first one.

How to expand first level children only of Treeview

I want to show all children of the first level on the treeview by default.
And then expand all children of those on click.
Try:
foreach (TreeNode tn in treeView1.Nodes) {
tn.Expand();
}
When adding nodes during runtime, you can just check the level and expand, if needed:
private void ShouldAutoExpand(TreeNode tn) {
if (tn.Level == 0)
tn.Expand();
}
There is no NodeAdded event you can hook into to check that automatically. You would have to determine yourself whether or not a node should be expanded "by default".
Update:
From your comment, it seems like you want to have all level 0 nodes expanded, but then expand all child nodes of level 1 when you expand them.
Try subscribing to the BeforeExpand event with this code:
private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e) {
treeView1.BeforeExpand -= treeView1_BeforeExpand;
if (e.Node.Level == 1) {
e.Node.ExpandAll();
}
treeView1.BeforeExpand += treeView1_BeforeExpand;
}
you can try something like this.. you will have to change the example to fit your own code since you neglected to paste any code that you have or attempted
private void addChildNode_Click(object sender, EventArgs e)
{
var childNode = textBox1.Text.Trim();
if (!string.IsNullOrEmpty(childNode)) {
TreeNode parentNode = treeView2.SelectedNode ?? treeView2.Nodes[0];
if (parentNode != null) {
parentNode.Nodes.Add(childNode);
treeView2.ExpandAll();
}
}
}
if you want a recursive, try this:
void expAll(TreeNode node)
{
node.Expand();
foreach(TreeNode i in node.Nodes)
{
expAll(i);
}
}
private TreeNode ExpandUptoLevel(TreeNode tn,int level)
{
if (level != 0)
{
level --;
tn.Nodes[0].Expand();
return ExpandUptoLevel(tn.FirstNode, level);
}
return tn;
}
To expand all nodes in a tree to a level the above code does not work. Just add a check to read and compare the actual node level to the level that you wish to expand to. Here's a code snippet.
private void ExpandUptoLevel(TreeNode tn, int level)
{
if (level >= tn.Level)
{
tn.Expand();
foreach (TreeNode i in tn.Nodes)
{
ExpandUptoLevel(i,level);
}
}
}
Only to open the first nodes:
for (int i = 0; i< treeView1.Nodes.Count; i++)
{
treeView1.Nodes[i].Expand();
}

C# help treeview and checkbox content

I really can't get out of this one.
I got treeview items in treeviews. The treeview items contain checkboxes with content. How do i get the content and put it in a list.
currently i got this
foreach (TreeViewItem item in treeView1.Items)
{
foreach (TreeViewItem childItem in item.Items)
{
CheckBox checkBoxTemp = childItem.Header as CheckBox;
if (checkBoxTemp == null) continue;
optieListBox.Items.Add(checkBoxTemp.Content);
}
}
I am not sure if i get your question correctly, but you can try this.
foreach (TreeViewItem childItem in item.Items)
{
CheckBox cbx = null;
//finds first checkbox
foreach(object child in childItem.Items){
cbx = child as CheckBox;
if (cbx != null) break;
}
ctrList.Items.Add(cbx.Content);
}
Bind your TreeView to a collection instead. That way you won't have to manipulate UI components to access the data, you will access the data directly.
The other way to do this is through recursion: Declare optieListBox list at class level and call GetContainers() method as an entry point call. optieListBox list should give you content list for all checked items in treeview.
List<string> optieListBox = new List<string>();
private List<TreeViewItem> GetAllItemContainers(TreeViewItem itemsControl)
{
List<TreeViewItem> allItems = new List<TreeViewItem>();
for (int i = 0; i < itemsControl.Items.Count; i++)
{
// try to get the item Container
TreeViewItem childItemContainer = itemsControl.ItemContainerGenerator.ContainerFromIndex(i) as TreeViewItem;
// the item container maybe null if it is still not generated from the runtime
if (childItemContainer != null)
{
allItems.Add(childItemContainer);
List<TreeViewItem> childItems = GetAllItemContainers(childItemContainer);
foreach (TreeViewItem childItem in childItems)
{
CheckBox checkBoxTemp = childItem.Header as CheckBox;
if (checkBoxTemp != null)
optieListBox.Items.Add(checkBoxTemp.Content);
allItems.Add(childItem);
}
}
}
return allItems;
}
private void GetContainers()
{
// gets all nodes from the TreeView
List<TreeViewItem> allTreeContainers = GetAllItemContainers(this.objTreeView);
// gets all nodes (recursively) for the first node
TreeViewItem firstNode = this.objTreeView.ItemContainerGenerator.ContainerFromIndex(0) as TreeViewItem;
if (firstNode != null)
{
List<TreeViewItem> firstNodeContainers = GetAllItemContainers(firstNode);
}
}
Try this:
List<string> values = new List<string>;
foreach (string node in treeView.Nodes)
{
values.Add(node);
}
//Loop through nodes
Also, if the tree view's nodes have children (nodes), try this instead:
List<string> values = new List<string>;
//Called by a button click or another control
private void getTreeValues(Object sender, EventArgs e)
{
foreach (string node in treeView.Nodes)
{
TreeNode child = (TreeNode)child;
values.Add(node)
getNodeValues(child);
}
foreach (string value in values)
{
Console.WriteLine(value + "\n");
}
}
//Recursive method which finds all children of parent node.
private void getNodeValues(TreeNode parent)
{
foreach (string child in parent.Nodes)
{
TreeNode node = (TreeNode)child;
values.Add(child);
if (nodes.Nodes.Count != 0) getNodeValues(child);
}
}

Categories