Search code examples
.netvb.netwinformstreeviewitem

Treeview node with more information


I am trying to custom info in the treeview node, so i made this class

Public Class TreeViewItem
    Inherits TreeNode
    Private _text As String
    Private _id As String
    Private _Data As String

    Sub New(id As String, name As String, data As String)
        MyBase.New()
        _text = Name
        _id = id
        _Data = data

    End Sub

    Public Shadows Property Text As String

        Get
            If Not String.IsNullOrEmpty(_Data) Then
                Return String.Format("{0} -> {1}", _text, _Data)
            Else
                Return _text
            End If
        End Get
        Set(value As String)
            _text = Name
        End Set
    End Property
    Public Property ID As String
        Get
            Return _id
        End Get
        Set(value As String)
            _id = value
        End Set
    End Property

    Public Property Data As String
        Get
            Return _Data
        End Get
        Set(value As String)
            _Data = value
        End Set
    End Property

End Class

however when i add a node like this

tv.Nodes.Add(New TreeViewItem(1, "hello", "hi"))

the text of the node is empty, any help with why it is not rendering?


Solution

  • You pretty much have to use the Text property of the base class, so try using an overload instead so that you can set the value:

    Public Overloads Property Text As String
      Get
        Return MyBase.Text
      End Get
      Set(value As String)
        _text = value
        If Not String.IsNullOrEmpty(_Data) Then
          MyBase.Text = String.Format("{0} -> {1}", value, _Data)
        Else
          MyBase.Text = value
        End If
      End Set
    End Property
    

    This would change your constructor to this:

    Sub New(id As String, name As String, data As String)
      MyBase.New()
      _id = id
      _Data = data
      _text = name
      Me.Text = _text
    End Sub
    

    And an update to your Data property:

    Public Property Data As String
      Get
        Return _Data
      End Get
      Set(value As String)
        _Data = value
        Me.Text = _text
      End Set
    End Property