Reputation: 305
I have a WinForm tree view (property is named "tvwAcct") where I would like to be able to search through all the existing nodes with a given string ("txtName.Text"), and if it already exists, to give the user a Message box warning to stop duplicate entries. It needs to be able to search all parent nodes and also child nodes. My current tree structure is as follows:
Bank account name
-> Sub-account name 1
-> Sub-account name 2
-> Sub-account name 3
I have looked at MSDN.Microsoft and can see that the Nodes.Find method exists.
Here is my code:
Private Sub txtName_Validating(eventSender As Object, eventArgs As CancelEventArgs) Handles txtName.Validating
Dim Cancel As Boolean = eventArgs.Cancel
Dim b As Boolean = True
' [ other 'if' conditions here ]
ElseIf (tvwAcct.Nodes.Find(txtName.Text, b) Then
MyMsgBox("Sorry, this account name already exists. Please try again with a different name.", MsgBoxStyle.Information)
Cancel = True
With this code, I get an error message which says:
Value of type TreeNode() cannot be converted to 'Boolean'.
I would be open to another way of doing this if this isn't going to work, such as getting the node text values, and then putting these into an Array list and querying the array list instead. But I'm not experienced enough to know how to do this.
Does anyone know where I've gone wrong please? Or can provide a better solution?
Upvotes: 2
Views: 1797
Reputation: 304
The Find method, search by node keys not text. So, if you need to search your nodes by text, you will need to implement your own method. I prefer to use LINQ for such tasks, however it may be not the optimum solution:
Dim treeNodes = tvwAcct.Nodes.Cast(Of TreeNode).Where(Function(x) x.Text = txtName.Text).ToArray
If treeNodes.Length > 0 Then
MessageBox.Show("Sorry, this account name already exists. Please try again with a different name.")
Cancel = True
End If
Upvotes: 1
Reputation: 81675
The TreeView.Nodes.Find function returns an array of nodes, not a true / false value.
Try it like this:
ElseIf tvwAcct.Nodes.Find(txtName.Text, b).Length > 0 Then
Upvotes: 3