I need to make a method that returns an array with the texts of all the nodes in the treeView, including all of them, children of children, etc., and excluding the nodes with the "idea" tag. How to implement it?
2 answers
List<string> allNodesNames = new List<string>(); foreach (TreeNode pNode in oYourTreeView.Nodes) PrintNodesRecursive(pNode, ref allNodesNames ); public void PrintNodesRecursive(TreeNode oParentNode, ref List<string> allNodesNames) { if ((string)oParentNode.Tag != "Idea") { allNodesNames.Add(oParentNode.Text); } // Start recursion on all subnodes. foreach(TreeNode oSubNode in oParentNode.Nodes) { PrintNodesRecursive(oSubNode, ref allNodesNames); } } |
Try to read this article with MSDN, there is an example of a recursive traversal of all nodes of the TreeView. You need to modify the code to be acceptable in your task, or here is an article with a more appropriate example (there, the Text property of all nodes is assembled into a string variable and not into an array, and there is no tag verification).
Here is a variant of the slightly modified code from the last example:
public partial class Form1 : Form { private List<string> nodesText; //Π‘ΠΏΠΈΡΠΎΠΊ Π΄Π»Ρ ΠΊΠΎΠ»Π»Π΅ΠΊΡΠΈΠΎΠ½ΠΈΡΠΎΠ²Π°Π½ΠΈΡ Π½Π°Π·Π²Π°Π½ΠΈΠΉ Π½ΠΎΠ΄ΠΎΠ² private string[] Result; //Π Π΅Π·ΡΠ»ΡΡΠΈΡΡΡΡΠΈΠΉ ΠΌΠ°ΡΡΠΈΠ² public Form1() { InitializeComponent(); //ΠΠ½ΠΈΡΠΈΠ°Π»ΠΈΠ·ΠΈΡΡΠ΅ΠΌ ΡΠΏΠΈΡΠΎΠΊ Π² ΠΊΠΎΠ½ΡΡΡΡΠΊΡΠΎΡΠ΅ ΡΠΎΡΠΌΡ: nodesText = new List<string>(); } private void Form1_Load(object sender, EventArgs e) { treeView1.ExpandAll(); } private void button1_Click(object sender, EventArgs e) { foreach (TreeNode n in treeView1.Nodes) { WalkTreeNode(n, 0); } //ΠΡΠ΅ΠΎΠ±ΡΠ°Π·ΡΠ΅ΠΌ ΡΠΏΠΈΡΠΎΠΊ Π² ΡΡΠ΅Π±ΡΠ΅ΠΌΡΠΉ ΠΌΠ°ΡΡΠΈΠ² Result = nodesText.ToArray(); //ΠΡΠ²ΠΎΠ΄ΠΈΠΌ ΡΠΎΠ΄Π΅ΡΠΆΠΈΠΌΠΎΠ΅ ΠΈΠΌΠ΅Π½Π½ΠΎ ΠΈΠ· ΠΌΠ°ΡΡΠΈΠ²Π°: MessageBox.Show(string.Join("\n", Result)); } private void WalkTreeNode(TreeNode node, Int32 level) { //ΠΡΠΎΠ²Π΅ΡΡΠ΅ΠΌ, Π΅ΡΡΡ Π»ΠΈ Ρ Π½Π°Ρ ΡΡΠΎ-ΡΠΎ Π² ΡΠ²ΠΎΠΉΡΡΠ²Π΅ Tag, ΠΈ Π΅ΡΠ»ΠΈ Π΅ΡΡΡ, Π½Π΅ ΡΠ°Π²Π½ΠΎ Π»ΠΈ ΡΡΠΎ Π·Π½Π°ΡΠ΅Π½ΠΈΡ "Idea", ΠΈ Π΅ΡΠ»ΠΈ ΡΡΠΎ ΡΠ°ΠΊ, ΡΠΎ Π΄ΠΎΠ±Π°Π²Π»ΡΠ΅ΠΌ ΡΠ΅ΠΊΡΡ Π½ΠΎΠ΄Ρ, Π° ΡΠ΅Π³ΠΈ Ρ "Idea" ΠΏΡΠΎΠΏΡΡΠΊΠ°Π΅ΠΌ. if (!(node.Tag != null && (string)node.Tag == "Idea")) { nodesText.Add(node.Text); } foreach (TreeNode n in node.Nodes) { WalkTreeNode(n, level + 1); } } } Everything.
- A good way, but I need without a global variable - Minebot
- @Minebot is a form class field, not a global variable. But not the essence in this context. Yes, and a more compact and beautiful answer has already been given ) - BlackWitcher
|