Find values in a VB array

1

I'm doing a task to find data in an array, in this example I have an array with values 01, 02, and 03.

What I do is put a value in a text box and in a FindKey function, indicate whether that value exists in the array. I do not know how I could be wrong since I only take the first value of the arrangement and therefore I always print the same message.

This is the code I have.

 Dim VectorA() As String = {"01", "02", "03"}

    Public Function buscarClaves(ByVal dts As String) As Boolean
        'buscarClaves = False
        For Each clave As String In VectorA
            If clave = dts Then
                Return True
            Else
                Return False
            End If
        Next
        '
    End Function

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        For i As Integer = 1 To VectorA.Length
            If buscarClaves(TextBox1.Text) Then
                MsgBox("Clave duplicado")
            Else
                MsgBox("Clave disponible")
            End If
        Next i
    End Sub
    
asked by Silvestre Silva 19.06.2018 в 01:30
source

1 answer

2

The for in the event of the Button is over, since you have a For Each that runs the entire array in the function, so it repeats the same value in the message, because it always finds the key in the three paths that does the length of the array.

And I made some changes to the searchKey function (). If you find the value returns true, but simply take the value you gave at the beginning, it is not necessary to add the else with the return false.

Public Class Form1
   Private VectorA() As String = {"01", "02", "03"}
   Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
      Try
         If buscarClaves(TextBox1.Text) Then
            MsgBox("Clave duplicado")
         Else
            MsgBox("Clave disponible")
         End If
      Catch ex As Exception
         MsgBox(ex)
      End Try
   End Sub
   Public Function buscarClaves(ByVal dts As String) As Boolean
      buscarClaves = False
      For Each clave As String In VectorA
         If clave = dts Then
            Return True
         End If
      Next
   End Function
End Class
    
answered by 19.06.2018 / 02:54
source