Getting all visible Nodes in a TreeView - c#

I want to get the node's keys just 'only in view' on treeview.
Here is the example;
I am using below code to get all node recursively. It just return all nodes key as expected. however i need to get the keys that only in treeview's view;
public void PrintNodesRecursive(UltraTreeNode oParentNode)
{
if (oParentNode.Nodes.Count == 0)
{
return;
}
foreach (UltraTreeNode oSubNode in oParentNode.Nodes)
{
MessageBox.Show(oSubNode.Key.ToString());
PrintNodesRecursive(oSubNode);
}
}
private void ultraButton3_Click(object sender, EventArgs e)
{
PrintNodesRecursive(ultraTree1.Nodes[0]);
}
I don't know i should follow different path or just reorganize code.
I just stacked after many hours. Need your help.

You can find the first visible node using Nodes collection and IsVisible property of the Node. Then create a recursive method which uses NextVisibleNode to find the next visible node in TreeView.
private void button1_Click(object sender, EventArgs e)
{
var visibleNodes = GetVisibleNodes(treeView1).ToList();
}
public IEnumerable<TreeNode> GetVisibleNodes(TreeView t)
{
var node = t.Nodes.Cast<TreeNode>().Where(x => x.IsVisible).FirstOrDefault();
while (node != null)
{
var temp = node;
node = node.NextVisibleNode;
yield return temp;
}
}
Also as another option, you can rely on Descendants extension method to flatten the TreeView and then using IsVisible property, get all visible nodes.

Related

showing tree node details separately in the same window

How can I show the details of a tree node, upon selection, in the same window but separately from the hierarchy tree.
So far I have successfully showed details in the treeview class using this code:
private void buttonCreateTree_Click(object sender, EventArgs e)
{
if (xd != null)
{
TreeNode rootNode = new TreeNode(xd.Root.FirstNode.ToString());
AddNode(xd.Root, rootNode);
treeView1.Nodes.Add(rootNode);
}
if (xd == null)
{
MessageBox.Show("No saved XML file!");
}
}
I've read about tags, but since I'm not very fond of Windows Forms, I don't know how to implement them correctly. What is the correct syntax for the solution?
Update: The details of a tree node are its child components with custom attributes i made like creationDate, LastAccessDate and LastModifiedDate so it needs to show the child elements of a tree node in the same window but apart from the hierarchy tree? that doesn't even make sense O.o
Not sure if that is what you want, or for that matter if you are but you can play with this:
Add a Panel panel1 to the form and hook up this event:
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
if (panel1.Controls.Count == 0)
{
panel1.Controls.Add(new TreeView());
panel1.Controls[0].Dock = DockStyle.Fill;
}
TreeView tv = panel1.Controls[0] as TreeView;
if (tv != null)
{
tv.Nodes.Clear();
// option 1 deep copy:
TreeNode tc = (TreeNode)e.Node.Clone();
tv.Nodes.Add(tc);
// option 2 shallow copy, 1 level
TreeNode tn = tv.Nodes.Add(e.Node.Text);
foreach (TreeNode cn in e.Node.Nodes)
tn.Nodes.Add(cn.Text);
}
tv.ExpandAll();
}
Do pick one of the two options and try..

Why when searching for an item in Tree View there is never a match?

In the textBox2 i type a word/string for example Hello and i checked Hello does exist but it never color it in Yellow. I used a breakpoint and it never pass this line and color it in Yellow: if (tn.Text == this.textBox2.Text)
private void FindByText()
{
TreeNodeCollection nodes = treeView1.Nodes;
foreach (TreeNode n in nodes)
{
FindRecursive(n);
}
}
private void FindRecursive(TreeNode treeNode)
{
foreach (TreeNode tn in treeNode.Nodes)
{
// if the text properties match, color the item
if (tn.Text == this.textBox2.Text)
tn.BackColor = Color.Yellow;
FindRecursive(tn);
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
FindByText();
}
EDIT
This is an example image of what i want to do: Free search text: I type in textBox2 for example na or hello and it will highlight anywhere the places hello for example. in nodes names in nodes childs inside nodes anyhwere just like it is in the image.
Ofcourse if i type only a or b or c don't highlight it but do highlight any string i type in the textBox2 that is longer then 2 letters
The image is only for example to show what i need to it to do:
You never check the top level, only the their children
(note: the way you do the comparison may need fixing as others have said, but that is a different issue.)
private void FindByText()
{
TreeNodeCollection nodes = treeView1.Nodes;
foreach (TreeNode n in nodes)
{
if (n.Text == this.textBox2.Text)
n.BackColor = Color.Yellow;
FindRecursive(n);
}
}
Use following code:
private void FindRecursive(TreeNode treeNode)
{
// Use this condition if you want a case sensitive search, else use treeNode.Text.ToLower() == this.textBox2.Text.ToLower()
if (treeNode.Text == this.textBox2.Text)
treeNode.BackColor = Color.Yellow;
else
treeNode.BackColor = Color.White; // Here use your default background color
foreach (TreeNode tn in treeNode.Nodes)
{
FindRecursive(tn);
}
}

Select TreeView Node

I've a TreeNode and I need to allow user to select only one child node for parent.
Example:
-Car
---Ferrari
---Lamborghini
---Porsche
-Shoes
---Nike
---Puma
---Adidas
I can select "Ferrari" and "Nike", but not other child in "Car" or "Shoes". How can I make it?
After I do this, I need to concat text of Parent and child like this: Car: Ferrari.
Can you help me?
Regards.
You could handle the BeforeCheck event and clear the siblings checkboxes, e.g. :
private bool skipEvents = false; // this flag to avoid infinite recursion
void treeView1_BeforeCheck(object sender, TreeViewCancelEventArgs e)
{
// if is a root (car or shoes), or it's a recursive call, just return
if (skipEvents || e.Node.Parent == null)
return;
skipEvents = true;
foreach (TreeNode sibling in e.Node.Parent.Nodes)
{
// set the other siblings to unchecked
if (sibling != e.Node)
sibling.Checked = false;
}
skipEvents = false;
}
Here's an example to concatenate the parents and childs selected:
public string GetSelectionString()
{
string categorySep = Environment.NewLine;
string parentChildSep = " : ";
StringBuilder sb = new StringBuilder();
foreach (TreeNode root in this.treeView1.Nodes)
{
foreach (TreeNode node in root.Nodes)
{
if (node.Checked)
{
if (sb.Length > 0)
sb.Append(categorySep);
sb.Append(root.Text);
sb.Append(parentChildSep);
sb.Append(node.Text);
break;
}
}
}
return sb.ToString();
}
for example if Ferrari and Puma are selected, it returns a string like this:
Car : Ferrari
Shoes : Puma
EDIT as per comment:
This code does what you ask in your comment (selection/deselection of parents children):
private bool skipEvents = false; // this flag to avoid infinite recursion
void treeView1_BeforeCheck(object sender, TreeViewCancelEventArgs e)
{
// if it's a recursive call, just return
if (skipEvents)
return;
skipEvents = true;
// it's a root (e.g. car or shoes)
if (e.Node.Parent == null)
{
// if root node is going to be checked, just cancel the action (i.e. block parent selection)
if (!e.Node.Checked)
{
e.Cancel = true;
}
}
else
{
foreach (TreeNode sibling in e.Node.Parent.Nodes)
{
// set the other siblings to unchecked
if (sibling != e.Node)
sibling.Checked = false;
}
}
skipEvents = false;
}
void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
{
// if it's a recursive call, just return
if (skipEvents)
return;
this.skipEvents = true;
// it's a root (e.g. car or shoes)
if (e.Node.Parent == null)
{
// root node has been unchecked, so uncheck the children
if (!e.Node.Checked)
{
foreach (TreeNode child in e.Node.Nodes)
child.Checked = false;
}
}
else
{
// if a child node has been checked --> check the parent
// otherwise, uncheck the parent
e.Node.Parent.Checked = e.Node.Checked;
}
this.skipEvents = false;
}
N.B.
TreeView class has a known bug that arises in Vista/Windows7 concerning checkboxes.
Basically if you double-click a checkbox it doesn't lauch any event, so this management will be compromised.
To solve this issue, you can disable double-click by using the class explained in this post instead of TreeView.
If you need one selection per tree, I would suggest using two TreeViews. I would also question whether or not you need to be using TreeViews or whether two ListBoxes or ComboBoxes might be more appropriate.
If you don't know how many 'trees' you'll have, but you do know how deep they are, you could use two or more ListBoxes (or ListViews) to display basically a list of lists:
Categories:
Shoes: Nike
Cars: Ferrari
Fruits: Apple (selected)
Selected Category (Fruits):
Apple (selected)
Orange
Pear
Kiwi

Filter a Treeview with a Textbox in a C# winforms app

I have a TreeView in my a C# winform. I would like to be able to add a search functionality through a search box.
Basically as the user types in letters (I'm guessing on the _TextChanged event), I show only the nodes that contain childnodes with the inputed letters...
My TreeView contains 53 parent nodes for a total of over 15000 Nodes so I need something a bit performant. I build my TreeView from a csv that I load into a DataTable and then make queries on to get the Parent nodes with associated child nodes...
UPDATE
I have an idea.
The final aim is that when a user doubleclicks on a child node it gets added to a listView.
I had first implemented this search function in a simple list view where I didn't separate my data into categories.
My idea is that once the user starts typing in things, I turn off my Tree view and show the list view instead...
I'll try and implement and see what it gives performance wise... Any critics on this idea are welcome.
Finally this is what I did, it suits my requirements.
I first make a copy of my TreeView and store into fieldsTreeCache. I then clear the fieldsTree. I then search through the cache and add any node containing my search parameter to the fieldsTree. Note here that once you search, you no longer have the parent nodes that show. You just get all of the end nodes. I did this because if not I had 2 choices:
Expand all the parent nodes containing childs that match but then it was slow and one parent might have 50 children which isn't great visually.
Not expand the parent nodes but then you just get the categories and not the children nodes that you're searching for.
void fieldFilterTxtBx_TextChanged(object sender, EventArgs e)
{
//blocks repainting tree till all objects loaded
this.fieldsTree.BeginUpdate();
this.fieldsTree.Nodes.Clear();
if (this.fieldFilterTxtBx.Text != string.Empty)
{
foreach (TreeNode _parentNode in _fieldsTreeCache.Nodes)
{
foreach (TreeNode _childNode in _parentNode.Nodes)
{
if (_childNode.Text.StartsWith(this.fieldFilterTxtBx.Text))
{
this.fieldsTree.Nodes.Add((TreeNode)_childNode.Clone());
}
}
}
}
else
{
foreach (TreeNode _node in this._fieldsTreeCache.Nodes)
{
fieldsTree.Nodes.Add((TreeNode)_node.Clone());
}
}
//enables redrawing tree after all objects have been added
this.fieldsTree.EndUpdate();
}
Here's a small simple example (with code from msdn) is that a very simple way to filter out the TreeView node displays.
winforms in a tree view you can only add or remove TreeNode.
The search for the nodes can still be improved if the nodes are stored with their data into a dictionary (with a unique key).
using System.Collections;
using System.Windows.Forms;
namespace FilterWinFormsTreeview
{
// The basic Customer class.
public class Customer : System.Object
{
private string custName = "";
protected ArrayList custOrders = new ArrayList();
public Customer(string customername) {
this.custName = customername;
}
public string CustomerName {
get { return this.custName; }
set { this.custName = value; }
}
public ArrayList CustomerOrders {
get { return this.custOrders; }
}
}
// End Customer class
// The basic customer Order class.
public class Order : System.Object
{
private string ordID = "";
public Order(string orderid) {
this.ordID = orderid;
}
public string OrderID {
get { return this.ordID; }
set { this.ordID = value; }
}
}
// End Order class
public static class TreeViewHelper
{
// Create a new ArrayList to hold the Customer objects.
private static ArrayList customerArray = new ArrayList();
public static void FilterTreeView(TreeView treeView1, string orderText) {
if (string.IsNullOrEmpty(orderText)) {
FillMyTreeView(treeView1);
} else {
// Display a wait cursor while the TreeNodes are being created.
Cursor.Current = Cursors.WaitCursor;
// Suppress repainting the TreeView until all the objects have been created.
treeView1.BeginUpdate();
foreach (TreeNode customerNode in treeView1.Nodes) {
var customer = customerNode.Tag as Customer;
if (customer != null) {
customerNode.Nodes.Clear();
// Add a child treenode for each Order object in the current Customer object.
foreach (Order order in customer.CustomerOrders) {
if (order.OrderID.Contains(orderText)) {
var orderNode = new TreeNode(customer.CustomerName + "." + order.OrderID);
customerNode.Nodes.Add(orderNode);
}
}
}
}
// Reset the cursor to the default for all controls.
Cursor.Current = Cursors.Default;
// Begin repainting the TreeView.
treeView1.EndUpdate();
}
}
public static void FillMyTreeView(TreeView treeView1) {
// Add customers to the ArrayList of Customer objects.
if (customerArray.Count <= 0) {
for (int x = 0; x < 1000; x++) {
customerArray.Add(new Customer("Customer" + x.ToString()));
}
// Add orders to each Customer object in the ArrayList.
foreach (Customer customer1 in customerArray) {
for (int y = 0; y < 15; y++) {
customer1.CustomerOrders.Add(new Order("Order" + y.ToString()));
}
}
}
// Display a wait cursor while the TreeNodes are being created.
Cursor.Current = Cursors.WaitCursor;
// Suppress repainting the TreeView until all the objects have been created.
treeView1.BeginUpdate();
// Clear the TreeView each time the method is called.
treeView1.Nodes.Clear();
// Add a root TreeNode for each Customer object in the ArrayList.
foreach (Customer customer2 in customerArray) {
var customerNode = new TreeNode(customer2.CustomerName);
customerNode.Tag = customer2;
treeView1.Nodes.Add(customerNode);
// Add a child treenode for each Order object in the current Customer object.
foreach (Order order1 in customer2.CustomerOrders) {
var orderNode = new TreeNode(customer2.CustomerName + "." + order1.OrderID);
customerNode.Nodes.Add(orderNode);
}
}
// Reset the cursor to the default for all controls.
Cursor.Current = Cursors.Default;
// Begin repainting the TreeView.
treeView1.EndUpdate();
}
}
}
Every node in TreeView has Expanded and IsVisible properties. The number of items which are visible at the same time is limited (TreeView.VisibleCount). Based on this information you can reduce the number of nodes to probe dramatically.
When scanning the node and it's child nodes you can abort recursion as you find the first match inside collapsed node, thus you already know it has at least one child and will be visible anyway.
Perform filtering asynchronously. (use new Task() for instance) Start the first task after minimal number of chars was typed (let's say 3). Every next typed char must cancel the running task and start the new one.

Umbraco: List Child Nodes in User Control

I have a user control in which I need to return child nodes based on parentID. I am able to get the parentID, but don't know the syntax for returning child nodes.
Getting child nodes is pretty straightforward.
Not sure how far you are with your code so here's a complete example with the various options:
using umbraco.presentation.nodeFactory;
namespace cogworks.usercontrols
{
public partial class ExampleUserControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
//If you just want the children of the current node use the following method
var currentNode = Node.GetCurrent();
//If you need a specific node based on ID use this method (where 123 = the desired node id)
var specificNode = new Node(123);
//To get the children as a Nodes collection use this method
var childNodes = specificNode.Children;
//Iterating over nodes collection example
foreach(var node in childNodes)
{
Response.Write(string.Format("{0}<br />", node.Name));
}
//To get the nodes as a datatable so you can use it for DataBinding use this method
var childNodesAsDataTable = node.ChildrenAsTable();
//Databind example
GridViewOnPage.DataSource = childNodesAsDataTable;
GridViewOnPage.DataBind();
}
}
}

Categories