0

I have a comboBox with items populating from a database(sql express). I want to prevent the users from saving the file with their own custom input. What I want is when saved is clicked then there is some prompt of some kind that says something like: "no valid item from the list was entered." Currently am using the leave event. This is the code:

  private void comboBox3_Leave(object sender, EventArgs e)
    {
        ComboBox cb = (ComboBox)sender;
        if (!comboBox3.Items.Contains(cb.Text))
        {
            MessageBox.Show("Not a valid Cari-med Item!");
        }

It works but am just asking to see if there are other ways to accomplish what am asking. I already tried changing the style to dropDownList upon my research. That method will not work for me because the user must be able to type and see the suggestions based on each character typed. Cannot have the user scrolling thru so much records. Is there any other way to accomplish this?

Javy26
  • 375
  • 1
  • 7
  • 22
  • You can simply set the `DropDownStyle` property to `DropDownList` to make sure the user can only select the values in the combobox and not enter free text. – Zohar Peled Dec 02 '16 at 14:25
  • I already stated in my explanation as to why I don't want that. The heading even starts off that says 100+ records..... @ZoharPeled – Javy26 Dec 02 '16 at 14:40
  • 1
    Sorry, I've misted that part... – Zohar Peled Dec 02 '16 at 14:42
  • You can just filter items on the fly when user types something and just force him to select something from the list – mrogal.ski Dec 02 '16 at 15:33
  • 1
    Showing a message box when the user tries to move to next control is not friendly (in fact is awkward). It's better to use `ErrorProvider` and `Validating` event. You will find this post useful: [Validation using Validating event and ErrorProvider - Show Error Summary](http://stackoverflow.com/a/33080822/3110834) – Reza Aghaei Dec 02 '16 at 22:48

1 Answers1

1

Instead of Leave event you can use Validating event and set e.Cancel = True if the item is not valid. If the event is canceled the focus remains on the ComboBox.

This is a simple example in VB.NET:

Private Sub ComboBox1_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles ComboBox1.Validating

    If Not CType(sender, ComboBox).Items.Contains(CType(sender, ComboBox).Text) Then
        MsgBox("Not a valid item!")
        e.Cancel = True
    End If

End Sub

If you want to do this in a Sub/Function you can check for a valid SelectedItem before executing your code:

If IsNothing(Me.ComboBox1.SelectedItem) Then
    MsgBox("Not a valid item!")
    Me.ComboBox1.Focus() 'optional step
Else
    'your save function
End If
tezzo
  • 10,858
  • 1
  • 25
  • 48
  • What if I want to include it in my saveTofile function? How would I do that? Because currently that is a function by itslelf – Javy26 Dec 02 '16 at 15:24