How to create a Key property for a TreeView node in Visual C# (322937)



The information in this article applies to:

  • Microsoft Visual C# .NET (2002)
  • Microsoft Visual C# 2005, Express Edition

This article was previously published under Q322937
For a Microsoft Visual Basic .NET version of this article, see 311318.

IN THIS TASK

SUMMARY

In earlier versions of the TreeView control, a TreeViewNode has a Key property where information that pertains to that node can be stored. You can use this key to refer to the objects in the Nodes collection. This is useful if the order of the objects in the collection can change, or if you need some type of indexed access to the underlying data. The version of the TreeView control that is included with Visual Studio .NET 2002 has no equivalent Key property.

If you want to use the Key property, you have two choices:
  • Use the Tag property of the TreeNode object if you must store simple information about the object.
  • If you require the collection-based indexing functionality, you can extend the TreeNode class and implement IDictionaryEnumerator.
This step-by-step article describes the second option and provides an example of how to extend the TreeNode class to add support for a Key property.

back to the top

Extend the TreeView control

  1. Create a new Windows Control Library project:
    1. Start Visual Studio .NET or Microsoft Visual Studio 2005.
    2. On the File menu, click New, and then click Project.
    3. In the Project Types list, click Visual C# Projects.

      Note In Visual Studio 2005, click Visual C# under Project Types.
    4. In the Templates list, click Windows Control Library.
    5. In the Name text box, type TreeViewEX, and then click OK.
    6. In Project Explorer, rename the default class module from UserControl1.cs to TreeViewEX.cs.
    7. In the Properties window for the user control, change the name of the control from UserControl1 to TreeViewEX.
  2. Inherit from the TreeView control. By default, a user control project inherits from System.Windows.Forms.UserControl. Change the class declaration so that it inherits from System.Windows.Forms.TreeView, as follows:

    NOTE: Do not modify the Component Designer generated code section.
    public class TreeViewEX : System.Windows.Forms.TreeView
    					
  3. Next, create a new TreeNode class that inherits from System.Windows.Forms.TreeNode. You can do this in the same TreeViewEX.cs class module, or you can create a separate Class module. This class also implements the IDictionaryEnumerator interface and adds support for enumerating the nodes from a collection. In this example, the existing TreeViewEX.cs class module is used for this new class. To create the class, add the following class definition to TreeViewEX.cs:
    public class TreeNode : System.Windows.Forms.TreeNode, IDictionaryEnumerator
    {
        private DictionaryEntry nodeEntry;
        private IEnumerator enumerator;
    
        public TreeNode()
        {
            enumerator = base.Nodes.GetEnumerator();
        }
    
        public string NodeKey
        {
            get
            {
                return nodeEntry.Key.ToString();
            }
    		
            set
            {			
                nodeEntry.Key = value;
            }
        }
    			
        public object NodeValue
        {
            get
            {
                return nodeEntry.Value;
            }
    
            set
            {
                nodeEntry.Value = value;
            }
        }
    
        public DictionaryEntry Entry
        {
            get
            {
                return nodeEntry;
            }
        }
    			
        public bool MoveNext()
        {
            bool Success;
            Success = enumerator.MoveNext();
            return Success;
        }
    
        public object Current
        {
            get
            {
                return enumerator.Current;
            }
        }
    			
        public object Key
        {
            get
            {
                return nodeEntry.Key;
            }
        }
    
        public object Value
        {
            get
            {
                return nodeEntry.Value;
            }
        }
    
        public void Reset()
        {
            enumerator.Reset();
        }
    }
    					
  4. This completes the extended TreeView control. Now verify that your project compiles with no errors by clicking Build Solution on the Build menu.
back to the top

Create the client application

  1. On the File menu, click New, and then click Project.
  2. In the Project Types list, click Visual C# Projects.

    Note In Visual Studio 2005, click Visual C# under Project Types.
  3. In the Templates list, click Windows Application.
  4. Add an instance of the TreeViewEX control to the default form of the Windows Application project:
    1. On the Tools menu, click Customize Toolbox.
    2. Click the .NET Framework Components tab.
    3. Click Browse, and then locate the TreeViewEX.dll file that was just created.
    4. Click OK.
    5. The TreeViewEX control is now located on the toolbox. Add an instance of this control to the form.
  5. Add two command buttons to the form.
  6. Paste the following code in the Load event of the form:
    this.treeViewEX1.Left = 10;
    this.treeViewEX1.Top = 10;
    this.treeViewEX1.Width = this.Width - 30;
    this.treeViewEX1.Height = (int)(this.Height * 0.6);
    this.treeViewEX1.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
    
    this.button1.Top = treeViewEX1.Height + 20;
    this.button1.Left = 10;
    this.button1.Width = 200;
    this.button1.Height = 50;
    this.button1.Text = "Add Items to TreeViewEx";
    
    this.button2.Top = button1.Top + button1.Height + 10;
    this.button2.Left = 10;
    this.button2.Width = 200;
    this.button2.Height = 50;
    this.button2.Text = "Locate Item in TreeView using the Key Value";
    this.Height = 400;
    					
  7. Paste the following code in the Click event of Button1:
    TreeViewEX.TreeNode tn;
    string myData;
    
    myData = "Extra Information pertaining to Node";
    
    tn = new TreeViewEX.TreeNode();
    tn.Text = "This is node 1";
    tn.NodeKey = "node1";
    tn.NodeValue = myData + " 1";
    treeViewEX1.Nodes.Add(tn);
    
    tn = new TreeViewEX.TreeNode();
    tn.Text = "This is node 2";
    tn.NodeKey = "node2";
    tn.NodeValue = myData + " 2";
    treeViewEX1.Nodes.Add(tn);
    
    tn = new TreeViewEX.TreeNode();
    tn.Text = "This is node 3";
    tn.NodeKey = "node3";
    tn.NodeValue = myData + " 3";
    treeViewEX1.Nodes.Add(tn);
    
    tn = new TreeViewEX.TreeNode();
    tn.Text = "This is node 4";
    tn.NodeKey = "node4";
    tn.NodeValue = myData + " 4";
    treeViewEX1.Nodes.Add(tn);
    
    tn = new TreeViewEX.TreeNode();
    tn.Text = "This is node 5";
    tn.NodeKey = "node5";
    tn.NodeValue = myData + "5";
    treeViewEX1.Nodes.Add(tn);
    
    tn = new TreeViewEX.TreeNode();
    tn.Text = "This is node 6";
    tn.NodeKey = "node6";
    tn.NodeValue = myData + " 6";
    treeViewEX1.Nodes.Add(tn);
    					
    Note The code should be changed in Visual Studio 2005. When you create a Windows Forms project, Visual C# adds one form to the project by default and names the form Form1. The two files that represent the form are called Form1.cs and Form1.designer.cs. You write your code in Form1.cs. The designer.cs file is where the Windows Forms Designer writes the code that implements all the actions that you performed by adding controls from the Toolbox. For more information about the Windows Forms Designer in Visual C# 2005, visit the following Microsoft Web site:
  8. Paste the following code in the Click event of Button2:
    // Locate the third node using the NodeKey.
    string myData;
    string nodeInfo;
    
    foreach (TreeViewEX.TreeNode tn in treeViewEX1.Nodes)
    {
        if (tn.NodeKey == "node6")
        {
            nodeInfo = "Name :" + tn.Text;
            myData = (string)tn.NodeValue;
            nodeInfo += "Data: " + myData;
    
            MessageBox.Show(nodeInfo, "Node Specific Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            break;
        }
    }
    					
  9. Click Add Items to TreeViewEX. This adds sample nodes to the TreeView and defines values for the key and data members.
  10. Click Locate Item. After you click this button, a message box appears and shows information about node 6 based on the use of the Key property in a foreach loop.
back to the top

Modification Type:MajorLast Reviewed:12/29/2005
Keywords:kbHOWTOmaster KB322937 kbAudDeveloper