C# Exercises

Home AgriMetSoft About Contact

TreeView Control in Winforms c#

	    
 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 TreeView_Control 
 { 
     public partial class Form1 : Form 
     { 
         bool init = false; 
         public Form1() 
         { 
             InitializeComponent(); 
             // Add parent node 
             TreeNode node = treeView1.Nodes.Add("root", "Government Space Agencies"); 
             // Add child node 
             TreeNode sub_node = node.Nodes.Add("country", "Country"); 
             // Add sub nodes 
             sub_node.Nodes.Add("usa", "United States").Nodes.Add("nasa", "National Aeronautics and Space Administration (NASA)"); 
             sub_node.Nodes.Add("chn", "China").Nodes.Add("cnsa", "China National Space Administration (CNSA)"); 
             sub_node.Nodes.Add("jpn", "Japan").Nodes.Add("jaxa", "Japan Aerospace Exploration Agency (JAXA)"); 
             sub_node.Nodes.Add("ind", "India").Nodes.Add("isro", "Indian Space Research Organization (ISRO)"); 
             sub_node.Nodes.Add("rus", "Russia").Nodes.Add("rfsa", "Russian Federal Space Agency (RFSA)"); 
             sub_node.Nodes.Add("dummy-node", "Dummy Node"); 
             // Expand all nodes 
             treeView1.ExpandAll(); 
         } 
   
         private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) 
         { 
             if (init) 
                 // Display the text of selected node 
                 MessageBox.Show("Text: " + e.Node.Text + " --- and Name: " + e.Node.Name); 
             init = true; 
         } 
   
         private void remove_node_Click(object sender, EventArgs e) 
         { 
             // Find for the item & remove it 
             var items = treeView1.Nodes.Find(node_rem.Text, true); 
             if (items.Length > 0) 
             { 
                 init = false; 
                 items[0].Remove(); 
                 init = true; 
             } 
             else 
                 MessageBox.Show("There is not any items with this name."); 
         } 
     } 
 } 
		
	 


Download the project of Visual Studio 2013 in DropBox Download


How to Use TreeView Control in Winforms C# | Fill Nodes and Select event


List of Exercises