create Treeview.nodes from textbox.text

ud2008

Well-known member
Joined
Jul 5, 2010
Messages
148
Programming Experience
Beginner
I've been trying to create a treeview from textbox text, but it's not working.
I have a treeview on a form and with the form-load event it automatically adds a root to the treeview (this works).
Then I have 3 textboxes, which I fill in and then click on the Add button.

The first textbox(FirstNameTextBox) adds an node to the root node.
Then the second textbox(FullNameTextBox) and third textbox(EmailTextBox) should add nodes to the just created node (from the FirstNameTextBox),
but here is when I receive an error.

I get the following error:
NullReferenceException was unhandled
Object reference not set to an instance of an object.

Here the code I use:
VB.NET:
Private Sub ButtonX2_Click(sender As System.Object, e As System.EventArgs) Handles ButtonX2.Click
        Dim First As New TreeNode()
        Dim Full As New TreeNode()
        Dim Email As New TreeNode()
        If TreeView1.SelectedNode IsNot Nothing Then
            First.Text = FirstNameTextBox.Text
            Full.Text = FullNameTextBox.Text
            Email.Text = EmailTextBox.Text
            TreeView1.SelectedNode.Nodes.Add(First)
            TreeView1.Nodes("First").Nodes.Add(Full)
            TreeView1.Nodes("First").Nodes.Add(Email)
            FirstNameTextBox.Text = ""
            FullNameTextBox.Text = ""
            EmailTextBox.Text = ""
        Else
            MessageBox.Show("Select a group to add the name to")
        End If
    End Sub

Thanks for any help.
 
TreeView1.Nodes("First").Nodes.Add(Full)
This will not work, because you don't have any node in the root node collection with that key.
What you seem to indend to do is this:
First.Nodes.Add(Full)

You can also simplify the code like this:
Dim node = TreeView1.SelectedNode.Nodes.Add(FirstNameTextBox.Text)
node.Nodes.Add(FullNameTextBox.Text)
node.Nodes.Add(EmailTextBox.Text)
 
Back
Top