.net 使用 ComboBox 的自动完成功能,同时将值限制为列表中的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/443569/
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
Using the AutoComplete feature of ComboBox, while limiting values to those in the list?
提问by Schmuli
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.
在 WinForms 2.0 中,ComboBox 具有自动完成功能,可显示自定义下拉列表,其中仅包含以输入文本开头的值。
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 DropDownStyleto DropDownList, which stops the user from entering a value.
但是,如果我想将有效值限制为仅出现在 ComboBox 的项目列表中的值,我可以通过将 设置为DropDownStyle来实现DropDownList,这会阻止用户输入值。
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.
是否有另一种方法来限制对列表的输入,同时仍允许使用自动完成功能?请注意,我已经看到了一些针对此的自定义解决方案,但我真的很喜欢匹配的自动完成项目显示在下拉列表中的方式,即使原始列表可能不是,也进行排序。
EDIT: I have thought about just validating the entered value, i.e. testing user input if it is valid in, say, the TextChangedevent, or even using the Validatingevent. 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?
编辑:我想过只验证输入的值,即测试用户输入是否在TextChanged事件中有效,或者甚至使用Validating事件。那么问题是预期的行为是什么?我是清除它们的值(空值也是无效的),还是使用默认值?最接近的匹配值?
P.s. Is there any other tags that I could add to this question?
Ps 还有其他标签可以添加到这个问题吗?
回答by Ecyrb
Have you tried setting AutoCompleteMode = AutoCompleteMode.SuggestAppendand AutoCompleteSource = AutoCompleteSource.ListItems? That lets the user type, but it only accepts words that are in the ComboBox. The only catch is that the behavior has changed for Win7 (see ComboBox.SelectedValue does not match displayed text when DropDownStyle = DropDownList in Windows 7).
你有没有试过设置AutoCompleteMode = AutoCompleteMode.SuggestAppend和AutoCompleteSource = AutoCompleteSource.ListItems?这允许用户输入,但它只接受ComboBox. 唯一的问题是 Win7 的行为已更改(请参阅ComboBox.SelectedValue 与 Windows 7 中的 DropDownStyle = DropDownList 时显示的文本不匹配)。
As for tags, you might try "combobox" and ".net".
至于标签,你可以试试“combobox”和“.net”。
回答by StevenC
This solution worked for me:
这个解决方案对我有用:
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
回答by StevenC
It might be as simple as this:
可能就这么简单:
Private Sub cbx_Validating(ByVal sender As Object, _
ByVal e As System.ComponentModel.CancelEventArgs) _
Handles cbxZip.Validating, cbxCity.Validating, cbxCountry.Validating
'Prerequisites: object: combobox, style: dropdownlist,
'autocompletesource=listitems, autocompletemode<>none
'check if the typed value is in the list, else cancel
'if the value isn't found, 'findstring' will return -1
'if cancel is set to True, one can't leave the field
e.Cancel = sender.FindStringExact(sender.Text) < 0
'make it obvious to the user there is an issue
If e.Cancel Then Beep()
End Sub
回答by user6586
You could hook the keypress or textchanged event and validate that the text entered was an initial substring match for at least one of the list items, rejecting the keypress (or deleting the most recent character) if not. The only issue I can think of with this is that it may be a bit confusing to the user that some input is not accepted (particularly when typing the first character, at which point the autocomplete list won't be visible yet, so they won't know what valid values are).
您可以挂钩 keypress 或 textchanged 事件并验证输入的文本是至少一个列表项的初始子字符串匹配,如果不是,则拒绝按键(或删除最近的字符)。我能想到的唯一问题是,某些输入不被接受可能会让用户有点困惑(特别是在输入第一个字符时,此时自动完成列表尚不可见,因此他们赢了不知道什么是有效值)。
Or just use it in dropdownlist mode - people can still type and it will jump to the first matching list item...
或者只是在下拉列表模式下使用它 - 人们仍然可以输入,它会跳转到第一个匹配的列表项......
回答by Meghag
You can set the "SuggestAppend property to SuggestAppend" and "AutoCompleteSource" to "ListItems" that will list and add the typed in characters by you in the drop down list. Also if not selected then even the apprpiate ValueMemeber would be selected for the drop down.
您可以将“SuggestAppend 属性设置为 SuggestAppend”并将“AutoCompleteSource”设置为“ListItems”,这将在下拉列表中列出并添加您键入的字符。此外,如果未选择,则甚至会为下拉列表选择合适的 ValueMemeber。
回答by JPCF
I've the same problem... I've asked the same question ( How to force a user to take a suggested entry into a ComboBox?) and then I implemented it with events, but I got a lot of code that can be improved by generalizing behavior... please tell me if you got it easily. Thanks!
我有同样的问题......我问了同样的问题(如何强制用户将建议的条目输入组合框?)然后我用事件实现了它,但我得到了很多可以通过概括行为来改进......请告诉我你是否很容易得到它。谢谢!
回答by Robert Groves
I was looking to do the same thing and came across this question. Here is what I've come up with.
我想做同样的事情并遇到了这个问题。这是我想出的。
Create a KeyDown event handler for the combobox and check for an Enter key. Note that after the user hits enter the text in the combobox is selected (as in, selected as if you were doing a cut or copy operation) and focus remains in the combobox.
为组合框创建 KeyDown 事件处理程序并检查 Enter 键。请注意,在用户点击后,组合框中的文本被选中(就像在执行剪切或复制操作一样被选中)并且焦点仍保留在组合框中。
If enter was pressed call a validation function that will do whatever you feel necessary if the value entered is good/bad.
如果按下回车键,则调用验证函数,如果输入的值好/坏,该函数将执行您认为必要的任何操作。
You can call this same function in a Leave event handler to prevent the user from leaving the combobox until a valid selection is made.
您可以在 Leave 事件处理程序中调用相同的函数,以防止用户在做出有效选择之前离开组合框。
private void uxWidgetsComboBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
ValidateSelection();
}
}
private void uxWidgetsComboBox_Leave(object sender, EventArgs e)
{
if(!ValidateSelection())
{
uxWidgetsComboBox.Focus();
}
}
Or something to that effect, but you get the idea.
或者类似的东西,但你明白了。
回答by Aaron Smith
The way I've done this is to check the value against the list of possible values when they leave the box and don't let them leave an invalid value. I don't know how you would want to handle it when you find that they've input an invalid value, but this is what I've done in the past.
我这样做的方法是在他们离开框时根据可能的值列表检查值,不要让他们留下无效值。我不知道当您发现他们输入了无效值时您会如何处理它,但这是我过去所做的。
回答by Weapon X
This worked for me. I used a DataTable as datasource
这对我有用。我使用 DataTable 作为数据源
With cbo
.AutoCompleteSource = AutoCompleteSource.ListItems
.AutoCompleteMode = AutoCompleteMode.SuggestAppend
End With
Private Sub cbo_Validating(sender As System.Object, e As System.ComponentModel.CancelEventArgs) Handles cbo.Validating
If cbo.SelectedItem Is Nothing Then
MessageBox.Show("Value entered not valid", "Message", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
e.Cancel = True
End If
End Sub

