vb.net 如何避免在 VB 的 Combobox 中添加重复项?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29931449/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 19:04:11  来源:igfitidea点击:

How to avoid adding duplicate items in a Combobox in VB?

vb.netcomboboxduplicatesitems

提问by MattC

I have a Combobox on my form for the user to select items in a drop-down box, also they are allowed to enter their own input. I need the user to add items to a combobox withoutadding a duplicate item already displayed.

我的表单上有一个组合框,供用户在下拉框中选择项目,也允许他们输入自己的输入。我需要用户将项目添加到组合框而不添加已显示的重复项目。

For example: the combobox has a list of dog breeds such as (pug, boxer, pitbull). So how do I not allow the user to enter "pug" when they type that into the combobox?

例如:组合框有一个狗品种列表,例如(哈巴狗、拳击手、比特犬)。那么,当用户在组合框中键入“pug”时,我如何不允许他们输入“哈巴狗”呢?

I'm coding in Visual Basic, Thank You!!!!

我正在用 Visual Basic 编码,谢谢!!!!

回答by Topman

i have tried it. This works.

我试过了。这有效。

And i am only assuming that u want an exceptionwhen duplicated valueis entered. Following is the code and it is in the Combobox1.Validatingevent.

而且我只是假设您在输入重复值时想要一个例外。以下是代码,它位于Combobox1.Validating事件中。

Private Sub ComboBox1_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles ComboBox1.Validating
        For Each item As String In ComboBox1.Items
            If item.ToLower.Contains(ComboBox1.Text.ToLower) Then
                MsgBox("Duplicate value: there's already '" & item & "' in the list. Please select from the list.", MsgBoxStyle.Exclamation, "Dog Breed")
                ComboBox1.Text = ""
                Exit For
            End If
        Next
    End Sub

For more information about Validatingevent, search for yourself. Thanks!

有关验证事件的更多信息,请自行搜索。谢谢!

回答by ABDUL MAJEED ALI

Use the code

使用代码

ComboBox1.items.clear()

under your code

在你的代码下