简体   繁体   中英

Checking for items in a drop down list of 100+ items

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM