简体   繁体   English

在超过100个项目的下拉列表中检查项目

[英]Checking for items in a drop down list of 100+ items

I have a comboBox with items populating from a database(sql express). 我有一个comboBox,其中包含从数据库(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. 我已经尝试在研究后将样式更改为dropDownList。 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. 如果项目无效,则可以使用Validating事件而不是Leave事件,并设置e.Cancel = True If the event is canceled the focus remains on the ComboBox . 如果事件被取消,焦点将停留在ComboBox

This is a simple example in VB.NET : 这是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: 如果要在Sub / Function执行此操作,则可以在执行代码之前检查有效的SelectedItem

If IsNothing(Me.ComboBox1.SelectedItem) Then
    MsgBox("Not a valid item!")
    Me.ComboBox1.Focus() 'optional step
Else
    'your save function
End If

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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