Articles

TreeViews And ByRefs

TreeNodes and ByRefs in VB.Net: a bug in .Net Framework?

I recently built a class that makes extensive use of recursive functions operating on TreeNodes. As I wanted to modify TreeNodes themselves, I thought I would use ByRef parameters in function definitions.

Here is a code example

Public Class MyForm
    Inherits System.Windows.Forms.Form
    WithEvents MyTreeView As New TreeView

    Private Sub MyForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.Controls.Add(MyTreeView)
        MyTreeView.CheckBoxes = True
        MyTreeView.Nodes.Clear()
        MyTreeView.Nodes.Add("Father")
        MyTreeView.Nodes(0).Nodes.Add("Child")
        MyTreeView.Nodes(0).Expand()
    End Sub

    Private Sub MyForm_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Click
        SwapNode(MyTreeView.Nodes(0).Nodes(0))
    End Sub

    Sub SwapNode(ByRef Node As TreeNode)
        Node.Checked = Not Node.Checked
        Microsoft.VisualBasic.MsgBox("MyTreeView.Nodes(0) contains " & MyTreeView.Nodes(0).Nodes.Count & " nodes.")
    End Sub
End Class

Just run this code: every time you click on the form, a new child is added to the treeview, alternatively checked and unchecked. I don't quite think that this is normal, but if anybody knows about this, I'll be delighted to understand.

CFP.