3

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.

CD Smith
  • 6,597
  • 7
  • 40
  • 66
JackSparrow
  • 389
  • 2
  • 8
  • 18
  • Usually setting the DropDownStyle to DropDownList would prevent that problem. – LarsTech Jun 15 '12 at 22:28
  • hi, yes I understand that but its not exactly what I was after – JackSparrow Jun 15 '12 at 22:37
  • As you said yourself, the code works. Not sure what help you are looking for at the moment. – LarsTech Jun 15 '12 at 22:41
  • ok, my combobox is populated with data - so for example the combobox contains fields Audi BMW Ford (as rows) so if I entered Mercedez and chose another control on the form it currently fails with the message box appearing which is excellent BUT if i click on the combobox and not enter anything in the combobox and I select another control on the form the message box appears when it shouldnt - so the message box should only appear if there is incorrect text in the combobox and not when the combobox is empty. – JackSparrow Jun 15 '12 at 22:49

2 Answers2

4

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
LarsTech
  • 80,625
  • 14
  • 153
  • 225
1

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
Hugo Dozois
  • 8,147
  • 12
  • 54
  • 58
Ken Mendes
  • 11
  • 2