问题描述
在WinForms 2.0中,ComboBox具有自动完成功能,只显示以输入文本开头的值的自定义下拉列表。
In WinForms 2.0, a ComboBox has an Auto-Complete feature, that displays a custom Drop-Down list with only the values that start with the entered text.
但是,如果我想限制有效值只有那些出现在ComboBox的项目列表,我可以通过设置 DropDownStyle
到 DropDownList
However, if I want to limit valid values to only those that appear in the ComboBox's list of items, I can do that by setting the
DropDownStyle
to DropDownList
, which stops the user from entering a value.
但是,现在我不能使用自动完成功能,这需要用户输入。
However, now I can't use the Auto-Complete feature, which requires user input.
有没有另一种方法来限制对列表的输入,同时仍然允许使用自动完成功能?注意,我已经看到了一些自定义解决方案,但我真的很喜欢匹配的自动完成项目显示在下拉列表中的方式,并排序,即使原始列表可能不是。
Is there another way to limit input to the list, while still allowing use of the Auto-Complete feature? Note that I have seen some custom solutions for this, but I really like the way the matching Auto-Complete items are displayed in a Drop-Down list, and sorted even though the original list may not be.
编辑:我已经考虑了只是验证输入的值,即测试用户输入,如果它在例如
TextChanged
事件中有效,甚至使用验证
事件。那么问题是什么是预期的行为?我清除其值(空值也无效),还是使用默认值?最接近的匹配值?
I have thought about just validating the entered value, i.e. testing user input if it is valid in, say, the
TextChanged
event, or even using the Validating
event. The question then is what is the expected behavior? Do I clear their value (an empty value is also invalid), or do I use a default value? Closest matching value?
P.s。
推荐答案
此解决方案适用于我:
Private Sub myComboBox_Validating(sender As System.Object, e As System.ComponentModel.CancelEventArgs) Handles myComboBox.Validating
If Not myComboBox.Items.Contains(myComboBox.Text) Then
MsgBox("Please select a value from the list", MsgBoxStyle.Exclamation, "Value not available")
e.Cancel = True
End If
End Sub
这篇关于使用ComboBox的自动完成功能,同时限制列表中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!