I have a treeview where some of the treenodes have a string saved into their tag object and some of the tags are left as nothing. Later on I want to use the strings for something, in the nodes where they exist.
For Each tn As TreeNode In TreeView1.Nodes
If Not String.IsNullOrWhiteSpace(tn.Tag) Then
Call DoTagStringStuff(tn.Tag)
End If
Next tn
This worked fine until I needed to turn on option strict to make my code compatible with a co-workers project. I'm a bit confused about how to best unbox the string from the treenode.tag object.
The error popup suggest using CStr
, but I was under the impression that the CStr
function was only in VB.net as a throwback to VB6, and really shouldn't be used for new code. If I try tn.Tag.toString
in the above code, I get an error at runtime when it fails to compute Nothing.toString
.
What is the right way to fix this? Should I even be using the tag object to hold string values in the first place, or is there a better treenode property that wouldn't require unboxing I can use for this?
Edit: I think perhaps this would be correct?
For Each tn As TreeNode In theNode.Nodes
If tn.Tag IsNot Nothing Then
Call DoTagStringStuff(DirectCast(tn.Tag, String))
End If
Next tn
Except I'm not checking for an empty or only whitespace string anymore.