0

I am working with ASP.Net Treeview and I need to check the existence of a node before adding a new node so that I don't have a duplication (which is what I am getting at the moment because of the state of the data.

I have tried TreeView1.FindNode(newNode.Text) which does get me a value if the nodes exists, but when trying to run a if statement on it to check its not nothing, or if it exists visual studio gives me an error to advise that cannot convert string to Boolean.

When trying

If Convert.ToBoolean(TreeView1.FindNode(node.Id)) = Nothing Then
                exists = False
            Else
                exists = True
End If

this always returns false even if it is not nothing

when trying

If TreeView1.FindNode(node.Id) = Nothing Then
                exists = False
            Else
                exists = True
End If`

this is where I get the error.

Any and all help would be very much appreciated.

thanks

1

1 Answer 1

2

The problem is TreeView1.FindNode returns TreeNode and you are trying to convert that to a boolean which will never work. This should work:-

If TreeView1.FindNode(node.Id) Is Nothing Then
      exists = False
Else
      exists = True
End If

Update:

You can also use a little bit of LINQ to find existance. I personally like this approach:-

Dim exist As Boolean = TreeView1.Nodes.OfType(Of TreeNode)() _
                                      .Any(Function(x) x.Value = node.Id)
Sign up to request clarification or add additional context in comments.

3 Comments

I realized this just before seeing your answer... anyone can feel free to mark me down for my utter stupidity
@SimonPrice - Hey its not stupidity, these things happens in coding world :) I have added one more approach by which we can find the existence of a treenode.
Thank you, I am able to find the parent with the initial attempt but I'm unable to find specific child nodes now so hopefully this new bit of code will help me too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.