How can i conver treeView1 selectednodes collection to List<string>? - c#

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);
}
}
}

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 find all the checked nodes in a Treeview using C#

This is the code which I am using, but I am always getting a blank string from the function.
How do I solve such a problem?
private string GetArrayofCheckedNodes()
{
string arrCheckedNodes = "";
ArrayList al = new ArrayList();
foreach (TreeNode node in TreeView1.Nodes)
{
if (node.Checked == true) // Checking whether a node is checked or not.
{
al.Add(node.Text);
}
}
for (int i = 0; i < al.Count; i++)
{
arrCheckedNodes += al[i].ToString() + " , ";
}
return arrCheckedNodes;
}
I'm assuming you want ALL checked nodes. TreeView1.Nodes only returns the first level so you will need to recurse down the tree. Also, you can use string.Join() to join the resultant values together.
private string GetArrayofCheckedNodes()
{
return string.Join(" , ", GetCheckedNodes(treeView1.Nodes));
}
public List<string> GetCheckedNodes(TreeNodeCollection nodes)
{
List<string> nodeList = new List<string>();
if (nodes == null)
{
return nodeList;
}
foreach (TreeNode childNode in nodes)
{
if (childNode.Checked)
{
nodeList.Add(childNode.Text);
}
nodeList.AddRange(GetCheckedNodes(childNode.Nodes));
}
return nodeList;
}

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.

Compare treeView nodes Text to a String

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;
}

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