Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Checking if item exists in TreeView before adding new item

Status
Not open for further replies.

ftpdoo

Programmer
Aug 9, 2001
202
0
0
GB
Hi,

I've got a TreeView called "lvwAddToGroup"

Before I add an item to this tree view I wish to check if it already exists in that tree view.

The item I'm check for it stored in "strFunctionCode".

Any idea's??
Thankx,
Jonathan
 
Use the strFunctionCode as the key value when adding nodes to the treeview. Then, attempt to add a new node to the treeview while trapping for errors that may occur. If an error is raised during the attempt to add a node, then you can be pretty sure one already exists with the same strFunctionCode:

On Error Resume Next
Set oNode = oTreeView.Nodes.Add('set whatever properties here)

If err.Number <> 0 Then
'An error was raised - node probably already exists
Else
'No error - node was created fine
End If
On Error Goto ErrHandler

Hope that helped. -Chris Didion
Matrix Automation, MCP
 
Loop through all the nodes..
You could use a function like this:

Private Function ItemExists(ByVal Text As String, ByVal CaseSensitive As Boolean) As Boolean

Dim loNode As Node
Dim lbRetval As Boolean

For Each loNode In lvwAddToGroup.Nodes
If CaseSensitive Then
If Text = loNode.Text Then
lbRetval = True
Exit For
End If
Else
If UCase$(Text) = UCase$(loNode.Text) Then
lbRetval = True
Exit For
End If
End If
Next loNode
ItemExists = lbRetval
End Function

And call it like this:

Dim lbExists As Boolean
lbExists = ItemExists(&quot;some node&quot;, False)

You can use the CaseSensitive parameter to determine whether &quot;some node&quot; is the same as &quot;Some Node&quot;..

Remedy
 
I would tend to do what Chris Didion has suggested, you need to use the string you are adding as the key to the treeview. Create a function that tries to access the node. If the function fails then you know the node does not exist. Looping around each node every time you want to add one seems a bit overkill.

Here's the one I use

Public Function TreeViewNodeExists(tvwTreeView As TreeView, strKey As String) As Boolean

Dim strTmp As String

On Error GoTo TreeViewNodeExists_Err

TreeViewNodeExists = False

strTmp = tvwTreeView.Nodes(strKey).Text

TreeViewNodeExists = True

TreeViewNodeExists_Exit:
Exit Function

TreeViewNodeExists_Err:
Resume TreeViewNodeExists_Exit
End Function

Hope this helps,

Chris Dukes
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top