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?

  • maybe add some code, what are you trying to do, what does not work? So perhaps it will be possible to give an answer. - Denis Bubnov

2 answers 2

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