JackSparrow
JackSparrow

Reputation: 389

Having problems trying to validate my combobox

I have decided to add some validation to my combobox, what I'm trying to achieve is to make sure that the user can ONLY enter fields that are in the combobox but the problem I have now is that if the user clicks on the combobox and doesnt enter anything and tries to leave the combobox the message box appears.

Private Sub Combobox1_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles Combobox1.Validating
    If Combobox1.Items.Contains(Combobox1.Text) = False Then
        e.Cancel = True
    End If
End Sub

Private Sub Combobox1_Leave(sender As Object, e As System.EventArgs) Handles Combobox1.Leave
    If Combobox1.Items.Contains(Combobox1.Text) = False Then
        Combobox1.Select()
        MessageBox.Show("select item from combobox")
    End If
End Sub

As stated before the coding does work, but I was trying to make sure the message box does not appear if the user doesnt enter anything in the combobox.

Upvotes: 3

Views: 7319

Answers (2)

Ken Mendes
Ken Mendes

Reputation: 11

Use this code:

Private Sub Combobox1_Leave(sender As Object, e As System.EventArgs) Handles Combobox1.Leave

    If ComboBox2.SelectedIndex = -1 Then
        MessageBox.Show("select item from combobox")
    End If
End Sub

Upvotes: 1

LarsTech
LarsTech

Reputation: 81610

Based on your comment, I think all you need to do is add a check for an empty string:

Private Sub ComboBox1_Validating(ByVal sender As Object, ByVal e As CancelEventArgs) Handles ComboBox1.Validating
  If ComboBox1.Items.Contains(ComboBox1.Text) = False Then      
    e.Cancel = (ComboBox1.Text <> String.Empty)
  End If
End Sub

Private Sub ComboBox1_Leave(ByVal sender As Object, ByVal e As EventArgs) Handles ComboBox1.Leave
  If Not ComboBox1.Items.Contains(ComboBox1.Text) Then
    If ComboBox1.Text <> String.Empty Then
      ComboBox1.Select()
      MessageBox.Show("select item from combobox")
    End If
  End If
End Sub

Upvotes: 4

Related Questions