I have treeview node, mynode, and want to set it as treeview's selected node. I use
tvw.selectedNode = mynode,
but it does not work, the selectedNode is still Nothing after the setting. Help please.
Printable View
I have treeview node, mynode, and want to set it as treeview's selected node. I use
tvw.selectedNode = mynode,
but it does not work, the selectedNode is still Nothing after the setting. Help please.
be sure mynode is not NOTHING.
This code creates a new node, adds it to the nodes collection of the tree, sets the selected node property and then uses the selectednode.text property to write a trace line, it works great.
VB Code:
Private Sub frmChild_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim myNode As New TreeNode("Root") Me.TreeView1.Nodes.Add(myNode) Me.TreeView1.SelectedNode = myNode Trace.WriteLine(Me.TreeView1.SelectedNode.Text) End Sub
Thanks all of you two.
myNode is not nothing.
to CyberHawke:
myNode is from my treeview, so it is there all the time, I can not add it to the tree again. All I want to do is to highlight it and expand its children.
This should work:
VB Code:
Private Sub frmChild_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim myNode As TreeNode = Me.TreeView1.Nodes(0) Me.TreeView1.SelectedNode = myNode myNode.Expand() Trace.WriteLine(Me.TreeView1.SelectedNode.Text) End Sub
that is what I have tried. no lucky so far.
This is what I am doing:
I click a node and save that node to a node variable, mynode. Then I go to a button to do something else, and the tree get reload with the same set of data. I want to set its selected node to mynode, but I get error "System.nullReferenceException occurred" on myNode.
That is because the reference that you had to the node is no longer valid, you wiped it out when you reloaded your tree.
would you tell me how to make that works?
Well, you would have to know something about the node that you were working with, what it's text is would be best if the text for all nodes is unique. Then you are left with basically walking the tree node by node (including child nodes) until you find it again.
The statement above assumes that something about your tree has changed so that you do not know the ordinal position of the node.
oh, i see. I need loop through all the nodes to find that one and set that node to selected.
correct
thank you for pushing me onto the right track.
Have a good day! :wave: