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
}
Related
This is what i tried:
List<string> filestodownload = new List<string>(treeViewMS1.SelectedNodes);
This is not working. treeViewMS1 is just like a regular treeView control but with multi nodes selection option.
The problem is how can i loop over the Selected Nodes and add the text property of each node to the List ?
Add recursive method if you want to search for checked nodes in depth.
private void GetNodesText(TreeNodeCollection tnc, List<string> selectednodes)
{
foreach (TreeNode node in tnc)
{
if (node.Nodes.Count > 0)
GetNodesText(node.Nodes, selectednodes);
if (node.Checked)
selectednodes.Add(node.Text);
}
}
And then call that method:
var selectednodes = new List<string>();
GetNodesText(treeView1.Nodes, selectednodes);
if (treeViewMS1.CheckedNodes.Count > 0)
{
List<string> _selectednodes = new List<string>();
foreach (TreeNode node in treeViewMS1.CheckedNodes)
{
if(node.Parent != null)
{
string checkedValue = node.Text.ToString();
_selectednodes.Add(checkedValue);
}
}
}
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.
I'm working on a Winform application, how can I check if there is a treeNode that its text is inside string Mystring? And how can i retrieve the tag of this node please?
if (myString.Contains(treeView1.Nodes.ToString()))
This works for only first matched node.
private TreeNode FindMatchedNode(TreeNodeCollection tnCol, string text)
{
TreeNode tn = null;
foreach (TreeNode node in tnCol)
{
if (text.ToLower().Contains(node.Text.ToLower()))
{
tn = node;
break;
}
else if (node.Nodes != null)
{
tn = FindNode(node.Nodes, text);
if (tn != null)
break;
}
}
return tn;
}
and for all matched nodes
private List<TreeNode> FindAllMatchedNodes(TreeNodeCollection tnCol, string text)
{
List<TreeNode> retVal = new List<TreeNode>();
foreach (TreeNode node in tnCol)
{
if (text.ToLower().Contains(node.Text.ToLower()))
{
retVal.Add(node);
}
else if (node.Nodes != null)
{
retVal.AddRange(FindNode(node.Nodes, text));
}
}
return retVal;
}
This method will traverse tree from root and find first node that Text is inside of myString
public object FindNode()
{
var queue = new Queue<TreeNode>();
foreach (var n in treeView1.Nodes)
{
// Add all root nodes to queue
queue.Enqueue(n);
}
while (queue.Count > 0)
{
// Take the next node from the front of the queue
var node = queue.Dequeue();
// Check if myString contains node text
if (myString.Contains(node.Text))
return node.Tag;
// Add the node’s children to the back of the queue
foreach (var child in node.Children)
{
queue.Enqueue(child);
}
}
// None of the nodes matched the specified string.
return null;
}
I need to expand my treeview based on a fullpath in c#
My tree view has 2 nodes which are collapsed and I want to expand Node A to number 3
so I have the fullpath of node A\1\2\3.
How can I step through and open each node based of the fullpath? Also the length of the fullpath may change, so i may need to open node be to level 6. So it needs to be done based on the fullpath. Any help would be great.
Node A
1
2
3
Node B
1
2
3
4 5 6
This is what I've tried:
TreeNode [] n= treeView1.Nodes.Find(search, true);
if (n.Length > 0)
found = true;
treeView1.Nodes[t].Collapse();
foreach (TreeNode p in n) {
string[] a = p.FullPath.Split('\\');
foreach (string b in a) {
treeView1.SelectedNode = treeView1.Nodes[b];
treeView1.SelectedNode.Expand();
I'm sorry for not commenting on above answer given by S3ddi9 which is CORRECT. I'm only adding something.
So the answer given by S3ddi9
...
string path = #"A\1\2\";
var path_list = path.Split('\\').ToList();
foreach (TreeNode node in treeView1.Nodes)
if (node.Text == path_list[0])
ExpandMyLitleBoys(node, path_list);
}
private void ExpandMyLitleBoys(TreeNode node, List<string> path)
{
path.RemoveAt(0);
node.Expand();
if (path.Count == 0)
return;
foreach (TreeNode mynode in node.Nodes)
if (mynode.Text == path[0])
{
ExpandMyLitleBoys(mynode, path); //recursive call
break; //this was missing in earlier answer
}
}
Does work, BUT you must add a BREAK (I marked it), because if the for loop doesn't finish, return; won't return you to your main function and it will throw you an exception because path[0] is null.
I hope this will be more simpler, for Treeviews the best approach is to use recursive methods
...
string path = #"A\1\2\";
var path_list = path.Split('\\').ToList();
foreach (TreeNode node in treeView1.Nodes)
if (node.Text == path_list[0])
ExpandMyLitleBoys(node, path_list);
}
private void ExpandMyLitleBoys(TreeNode node, List<string> path)
{
path.RemoveAt(0);
node.Expand();
if (path.Count == 0)
return;
foreach (TreeNode mynode in node.Nodes)
if (mynode.Text == path[0])
ExpandMyLitleBoys(mynode, path); //recursive call
}
this does the work perfectly
Cracked it!!
TreeNode[] n = treeView1.Nodes.Find(search, true);
if (n.Length > 0)
found = true;
treeView1.Nodes[t].Collapse();
foreach (TreeNode p in n)
{
i = 0;
string[] a = p.FullPath.Split('\\');
foreach (string b in a)
{
if (i == 0)
{
treeView1.SelectedNode = treeView1.Nodes[b];
current = treeView1.Nodes[b];
treeView1.SelectedNode.Expand();
i = 1;
}
else
{
treeView1.SelectedNode = current.Nodes[b];
current = current.Nodes[b];
treeView1.SelectedNode.Expand();
if (b.ToUpper().Contains(search))
{
treeView1.SelectedNode.BackColor = System.Drawing.Color.Red;
}
I wrote a little simpler routine that works great. no recursion at all...
This assumes your path is a full file path like... "C:\program files\myapp" and when you add your nodes you set the node Key equal to the folder name
string[] strFolders = strPath.Split('\'));
System.Windows.Forms.TreeNode CurrentNode = null;
System.Windows.Forms.TreeNode[] FoundNodes = null;
foreach (string folder in strFolders) {
if (!folder.Contains(":")) {
if (CurrentNode == null) {
FoundNodes = treeFolders.Nodes.Find(folder, false);
} else {
FoundNodes = CurrentNode.Nodes.Find(folder, false);
}
if (FoundNodes.Length > 0) {
CurrentNode = FoundNodes[0];
CurrentNode.Expand();
} else {
//no folder found. cant continue
break;
}
}
}
if (CurrentNode != null) {
treeFolders.SelectedNode = CurrentNode;
}
i got this tree view and i made it to select all children if parent is checked, the way back as well. There's another rule to check some dependent child too. The problem is: I want to check the parent if any child is checked, but because those other rules i can't find a way to do that without the rules get conflict. So here's is the code i've made until now:
private void tvMorgan_AfterCheck(object sender, TreeViewEventArgs e)
{
//Check Children if parent checked
if (e.Node.Nodes.Count > 0)
{
TreeNode tnParent = e.Node;
if (tnParent.Checked)
{
foreach (TreeNode tnChild in tnParent.Nodes)
{
tnChild.Checked = true;
}
}
//Unchecked children if parent unchecked
else
{
foreach (TreeNode tnChild in tnParent.Nodes)
{
tnChild.Checked = false;
}
}
}
//If dependent node is selected, check the other two
else if (((e.Node.Text.Contains("BRL/EUR")) && (e.Node.Checked)) && (e.Node.Parent.Text.Contains("FWD")))
{
TreeNode tnParent = e.Node.Parent;
foreach (TreeNode tn in tnParent.Nodes)
{
if (tn.Text.Contains("BRL/USD") || tn.Text.Contains("EUR/USD"))
tn.Checked = true;
}
}
//If one of the two necessary nodes are uncheked, then uncheck the dependent one
else if ((((e.Node.Text.Contains("BRL/USD")) || (e.Node.Text.Contains("EUR/USD"))) && (!e.Node.Checked)) && (e.Node.Parent.Text.Contains("FWD")))
{
TreeNode tnParent = e.Node.Parent;
foreach (TreeNode tn in tnParent.Nodes)
{
if (tn.Text.Contains("BRL/EUR"))
tn.Checked = false;
}
}
}
Thanks in advance
The documentation of the TreeView.AfterCheck Event shows exactly how to do what you are looking for