0
votes

I have a form with a ComboBox and a button. when the button is clicked, it's event should check that ComboBox has a value before proceeding. ComboBox has a default value set:

  • Name=cmbName,
  • Default Value = "Joe",
  • RowSource=SELECT name FROM table ORDER BY name;

This is what I tried:

Private Sub btnOk_Click()
    If (CmbName.ListIndex = -1)Then
        Exit Sub
    End If
    'Do Something
End Sub 

But every time I click the button, cmbName.ListIndex does equal -1, and the sub is exited even though there is a default value.

2

2 Answers

1
votes

Not sure if I'm misunderstanding something; you can just use the IsNull() function.

If the user has changed the value away from the default value, back to a null value, then this will return True.

Private Sub btnOk_Click()
    If IsNull(CmbName.Value) Then
        Exit Sub
    End If
    'Do Something
End Sub 
0
votes

ListIndex is a property of ComboBox. It returns the index of the chosen value in the list. For example: If the first value is selected, comboBox.listIndex = 0. If there is no value, then comboBox.listIndex = -1.

If the user doesn't select a value from the list, then the value is the default "joe".

If the query SELECT name FROM table ORDER BY name returns a list in which there is no value "joe", then listIdex will still be -1.

Try:

If (CmbName.ListIndex = -1) And (Trim(CmbName.Value & "") = "")

Will return true if no value was selected and the box is empty.