I am working on Windows Form Application C#, When i check few treeview Nodes and on Button Click Event, Text corresponding to each Treenode will be Append to richtextbox.
I had done similar thing while Select Treenode, Ex:
if(treeView1.SelectedNode.Name == "First Node")
this.richTextBox1.SelectedText = Firstline;
elseif(treeView1.SelectedNode.Name == "Second Node")
this.richTextBox1.SelectedText = Other Text;
But i need to do similar activity for Multiple Checked Node from my treeview (On Button press event).
Please help me
as your question is not clear . assuming
you have winform with treeView1Control
//populating treeView with dummy data
private void Form2_Load(object sender, EventArgs e)
{
//set the check box true
treeView1.CheckBoxes = true;
TreeNode treeNode = new TreeNode("Windows");
treeView1.Nodes.Add(treeNode);
//
// Another node following the first node.
//
treeNode = new TreeNode("Linux");
treeView1.Nodes.Add(treeNode);
//
// Create two child nodes and put them in an array.
// ... Add the third node, and specify these as its children.
//
TreeNode node2 = new TreeNode("C#");
TreeNode node3 = new TreeNode("VB.NET");
TreeNode[] array = new TreeNode[] { node2, node3 };
//
// Final node.
//
treeNode = new TreeNode("Dot Net Perls", array);
treeView1.Nodes.Add(treeNode);
}
private void button3_Click(object sender, EventArgs e)
{
string text = traverseTreeAngGetName(treeView1.Nodes);
this.richTextBox1.SelectedText = text;
}
/// <summary>
/// it will traverse all the tree Node from 1 to N Level. if Node is Checked then get
/// the checked node name.
/// </summary>
/// <param name="tr"></param>
/// <returns></returns>
public static string traverseTreeAngGetName(TreeNodeCollection tr){
string str = "";
foreach (TreeNode node in tr) {
if (node.Checked) {
//here you can append any text on the base of current
str += node.Text + " - " ;
}
str += traverseTreeAngGetName(node.Nodes);
}
return str;
}
Related
I am working with Windows Form project. I am using VS2013 and .net version is 4.5. i do not have very high knowledge in .Net.
I want to up down any node of my tree view which was possible from this post https://stackoverflow.com/a/2204091/14326209
Here is the code
/// <summary>
/// Move Selected Node Up in TreeNode Collection
/// </summary>
/// <param name="node"></param>
public static void MoveUp(this TreeNode node)
{
TreeNode parent = node.Parent;
TreeView view = node.TreeView;
if (parent != null)
{
int index = parent.Nodes.IndexOf(node);
if (index > 0)
{
parent.Nodes.RemoveAt(index);
parent.Nodes.Insert(index - 1, node);
node.Text = node.Text;
}
}
else if (node.TreeView.Nodes.Contains(node)) //root node
{
int index = view.Nodes.IndexOf(node);
if (index > 0)
{
view.Nodes.RemoveAt(index);
view.Nodes.Insert(index - 1, node);
node.Text = node.Text;
}
}
//view.Focus();
//view.SelectedNode = node;
//node.EnsureVisible();
}
/// <summary>
/// Move Selected Node Down in TreeNode Collection
/// </summary>
/// <param name="node"></param>
public static void MoveDown(this TreeNode node)
{
TreeNode parent = node.Parent;
TreeView view = node.TreeView;
if (parent != null)
{
int index = parent.Nodes.IndexOf(node);
if (index < parent.Nodes.Count - 1)
{
parent.Nodes.RemoveAt(index);
parent.Nodes.Insert(index + 1, node);
node.Text = node.Text;
}
}
else if (view != null && view.Nodes.Contains(node)) //root node
{
int index = view.Nodes.IndexOf(node);
if (index < view.Nodes.Count - 1)
{
view.Nodes.RemoveAt(index);
view.Nodes.Insert(index + 1, node);
node.Text = node.Text;
}
}
//view.Focus();
//view.SelectedNode = node;
//node.EnsureVisible();
}
private void tvCsmTuner_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Up)
{
tvCsmTuner.SelectedNode.MoveUp();
}
else if (e.KeyCode == Keys.Down)
{
tvCsmTuner.SelectedNode.MoveDown();
}
label3.Focus();
}
when i call Node.MoveDown() and Node.MoveUp() then Node is getting perfectly moving but selection from Selected node going to different node after node moved. i want selection should persist on selected node after moving the Node.
So please guide me what changes need to add in the above code as a result selection on selected node should not go to any node.
I tried this to persist node selection but did not work.
view.SelectedNode = node;
Looking for suggestion. thanks
I have an application that allows users to add new items into a TreeView control. When an item is selected the parent node reveals its child nodes, but it collapses when a new item (Button is clicked) is added to the Treeview control. I want it to stay expanded until the user interacts with it again.
//List<> collection is initialized
//Public class property is created to set it's member variables to the control values that the user enters
private void addButton_Click(object sender, EventArgs e)
{
if (ComboBoxOne.SelectedIndex != 0)
{
//Method that adds new item to a List<> Collection
AddToList();
//Method that goes through the List<> Collection, modifies the display of the item and adds it to the TreeView control
AddToTreeView();
}
}
//How I am adding the List<> objects to the treeview control
private void TravelTreeView()
{
TreeView1.Nodes.Clear();
//Items is the class I created and ObjectList is the List<>
foreach (Items obj in ObjectList)
{
TreeNode node = new TreeNode();
node.Text = obj.Name;
//Imagelist has 7 images
node.SelectedImageIndex = 0;
node.ImageIndex = obj.NameImage;
node.Nodes.Add(obj.AgeImage, "Age: " + obj.Age, 5);
node.Nodes.Add(obj.ZodiacImage, "Zodiac: " + obj.Zodiac, 6);
node.Nodes.Add(obj.JobImage, "Job: " + obj.Job, 7);
TreeView1.Nodes.Add(node);
}
}
I see that TreeView is cleared and then populated with list of nodes. As mentioned in the comment(s) you may check for IsExpanded property and then decide to call Expand on TreeNode.
Another way: As you are adding many new TreeNodes I would assume there is no previous state for these nodes to check for IsExpanded, in such a case, you may try something like below, the new Node is added in expanded state. Note Beginupdate/EndUpdate calls.
private void TravelTreeView()
{
// better to do this to avoid too many repaints
TreeView1.BeginUpdate();
TreeView1.Nodes.Clear();
//Items is the class I created and ObjectList is the List<>
foreach (Items obj in ObjectList)
{
TreeNode node = new TreeNode();
node.Text = obj.Name;
//Imagelist has 7 images
node.SelectedImageIndex = 0;
node.ImageIndex = obj.NameImage;
node.Nodes.Add(obj.AgeImage, "Age: " + obj.Age, 5);
node.Nodes.Add(obj.ZodiacImage, "Zodiac: " + obj.Zodiac, 6);
node.Nodes.Add(obj.JobImage, "Job: " + obj.Job, 7);
// add an expanded Node
node.Expand();
TreeView1.Nodes.Add(node);
}
// we are done with the updates to TreeView
TreeView1.EndUpdate();
}
WinForms does retain the state of the controls. The issue here seems to be the fact that you clean the items and then iterate your object and then reload the TreeView. In this case the items would be collapsed which is the default.
I would suggest the below approach,
private void TravelTreeView()
{
//Items is the class I created and ObjectList is the List<>
foreach (Items obj in ObjectList)
{
//Check to see if the item already exists
if (!TreeView1.Nodes.ContainsKey(obj.Name))
{
var node = new TreeNode();
node.Text = obj.Name;
//Imagelist has 7 images
node.SelectedImageIndex = 0;
node.ImageIndex = obj.NameImage;
node.Nodes.Add(obj.AgeImage, "Age: " + obj.Age, 5);
node.Nodes.Add(obj.ZodiacImage, "Zodiac: " + obj.Zodiac, 6);
node.Nodes.Add(obj.JobImage, "Job: " + obj.Job, 7);
TreeView1.Nodes.Add(node);
}
}
}
Information on the ContainsKey Method on TreeNodeCollection
I have a new form with a treeView1 and a textBox1.
I want that when i type a word in the textBox1 if it will match the word in any of the items in any of the nodes highlight this word.
For example if i type hello in the textBox1 it will find all the places hello exist.
But if i type only h or he it should not highlight the words hello
And maybe to add Enter key for the textBox1 or a button click event to confirm when searching.
Now i'm using textBox1_TextChanged event but i'm not sure if thats a good idea.
In general i want to search for words in all Lists items in the treeView.
Now when i just type a letter/char in the textBox1 it's jumping to the treeView1 and collapse places i didn't want it to. Not working as i wanted.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ScrollLabelTest
{
public partial class DisplayResponses : Form
{
TreeNode[] treeNodes;
private List<string> nodesNames = new List<string>();
private List<TreeNode> CurrentNodeMatches = new List<TreeNode>();
private int LastNodeIndex = 0;
private string LastSearchText;
public DisplayResponses()
{
InitializeComponent();
addmore();
}
public void addmore()
{
foreach (List<string> l_branch in ListsExtractions.responsers)
{
TreeNode l_node = treeView1.Nodes.Add(l_branch[l_branch.Count - 1]);
for (int l_count = 0; l_count < l_branch.Count - 1; l_count++)
{
l_node.Nodes.Add(l_branch[l_count]);
}
}
}
private void DisplayResponses_Load(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
foreach (TreeNode tn in treeView1.Nodes)
{
/*if (textBox1.Text == tn.Text)
{
MessageBox.Show(tn.Text);
}*/
int positionOfDream = tn.Text.IndexOf(textBox1.Text);
if (positionOfDream != -1)
{
string name = tn.Text.Substring(positionOfDream, textBox1.Text.Length);
if (textBox1.Text == tn.Text)
{
MessageBox.Show(tn.Text);
}
}
}
}
}
}
}
In this part:
if (textBox1.Text == tn.Text)
{
MessageBox.Show(tn.Text);
}
It was working it was Showing the name of a node when i typed the complete name of a node.
Now in this part:
int positionOfDream = tn.Text.IndexOf(textBox1.Text);
if (positionOfDream != -1)
{
string name = tn.Text.Substring(positionOfDream, textBox1.Text.Length);
if (textBox1.Text == tn.Text)
{
MessageBox.Show(tn.Text);
}
}
I want that if i type the complete node name or if i type a part of node name it will Show it or any other nodes that have this part of name too.
For example if the node name is: Hello world
If i typed Hello it will show me Hello world and also other nodes names that have the word Hello inside
But if i type only H don't show me all the nodes with H in the name.
After this part will work i want to add another part that when i type in the textBox1 any string not one letter but a string for example: Hello
So it will search in all nodes but not the names of the nodes but inside each node tree.
For example i have a node name: Hello World
If i click on the '+' near it it will collapse and show me like 70 items/child nodes.
I want to search on this 70 items/child nodes for the string i type in the textBox1.
A string/word should be from three letters and on. If i type something less then three letters don't search in the 70 items/child nodes but keep searching in the nodes names like above.
Here are code that will search all the nodes for a full match and highlight the background red:
private void textBox1_TextChanged(object sender, EventArgs e)
{
foreach (TreeNode tn in treeView1.Nodes)
{
Call(tn);
}
}
private void Call(TreeNode treeNode)
{
if (treeNode.Text == textBox1.Text)
{
treeNode.BackColor = Color.Red;
}
else
{
treeNode.BackColor = Color.White;
}
foreach (TreeNode tn in treeNode.Nodes)
{
Call(tn);
}
}
Partial answer.
"A string/word should be from three letters and on."
To get it to run only when 3 letters or more have been typed change
if (textBox1.Text != "")
to
if (textBox1.TextLength >= 3)
{
//search child items only
}
else
{
//search items only
}
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.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
i have one treeview and 2 button
i want when click on UP_button, above Node selected if i am click on DOWN_button then selection should be go down
There are some nice built in properties of the node that you can use, so for up you would use:
TreeView.SelectedNode = TreeView.SelectedNode.PrevNode;
and for down:
TreeView.SelectedNode = TreeView.SelectedNode.NextNode;
From MSDN Documentation:
private void SelectNode(TreeNode node)
{
if(node.IsSelected)
{
// Determine which TreeNode to select.
switch(myComboBox.Text)
{
case "Previous":
node.TreeView.SelectedNode = node.PrevNode;
break;
case "PreviousVisible":
node.TreeView.SelectedNode = node.PrevVisibleNode;
break;
case "Next":
node.TreeView.SelectedNode = node.NextNode;
break;
case "NextVisible":
node.TreeView.SelectedNode = node.NextVisibleNode;
break;
case "First":
node.TreeView.SelectedNode = node.FirstNode;
break;
case "Last":
node.TreeView.SelectedNode = node.LastNode;
break;
}
}
node.TreeView.Focus();
}
EDIT
You'd of course use the cases for "Previous" and "Next" or "PreviousVisible" and "NextVisible" in your button click handlers. This code assumes that you select the "action" from a combo box and push a button.
EDIT 2
Just in case you are trying to move the nodes up and down (not the selection), you can use something like the following:
TreeNode sourceNode = treeView.SelectedNode;
if (sourceNode.Parent == null)
{
return;
}
treeView.Nodes.Remove(sourceNode);
treeView.Nodes.Insert(sourceNode.Index + 1, sourceNode);
This would move the current node one down. Please note that you have to write some more code to handle some special cases (e.g. what happens with the first node? Does it work on all levels of the tree?), but basically that's what I'd try.
try this for UP:
private void btnUP_Click(object sender, EventArgs e)
{
var tn = tv.SelectedNode;
if(tn==null) return;
var idx = tn.Index;
txt.Text = "Node: " + idx;
var par = tn.Parent;
if(par==null) return;
par.Nodes.Remove(tn);
if (idx > 0)
{
par.Nodes.Insert(tn.Index - 1, tn);
return;
}
//if you want to move int its parent's parent [grand parent :) ]
if (par.Parent!=null)
par.Parent.Nodes.Add(tn);
}
For ASP.NET Treeview:
/// <summary>
/// MoveComponentUpLinkButton_Click
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void MoveComponentUpLinkButton_Click(object sender, EventArgs e)
{
// Get the selected node
TreeNode sourceNode = this.MyTreeview.SelectedNode;
if (sourceNode != null)
{
// Get the selected node's parent
TreeNode parentNode = this.MyTreeview.SelectedNode.Parent;
if (parentNode != null)
{
int index = -1;
// For each node in selected nodes parent
for (int j = 0; j < parentNode.ChildNodes.Count; j++)
{
// If we found the selected node
if (sourceNode == parentNode.ChildNodes[j])
{
// save index
index = j;
break;
}
}
// If node is not already at top of list
if (index > 0)
{
// Move it up
parentNode.ChildNodes.RemoveAt(index);
parentNode.ChildNodes.AddAt(index - 1, sourceNode);
sourceNode.Selected = true;
}
}
}
}
/// <summary>
/// MoveComponentDownLinkButton_Click
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void MoveComponentDownLinkButton_Click(object sender, EventArgs e)
{
// Get the selected node
TreeNode sourceNode = this.MyTreeview.SelectedNode;
if (sourceNode != null)
{
// Get the selected node's parent
TreeNode parentNode = this.MyTreeview.SelectedNode.Parent;
if (parentNode != null)
{
int index = -1;
// For each node in selected nodes parent
for (int j = 0; j < parentNode.ChildNodes.Count; j++)
{
// If we found the selected node
if (sourceNode == parentNode.ChildNodes[j])
{
// save index
index = j;
break;
}
}
// If node is not already at botton of list
if (index < parentNode.ChildNodes.Count - 1)
{
// Move it down
parentNode.ChildNodes.RemoveAt(index);
parentNode.ChildNodes.AddAt(index + 1, sourceNode);
sourceNode.Selected = true;
}
}
}
}
my problem solved.
thanx for answers
private void button1_Click(object sender, EventArgs e)
{
TreeNode node = new TreeNode();
node = treeView1.SelectedNode;
treeView1.SelectedNode = node.NextVisibleNode;
node.TreeView.Focus();
}