我正在使用 .NET Framework 4.0 通过 VB 开发 VS 2010
我有一个组合框
。它里面有一些项目并且显示得很好。这就是有点奇怪的地方:
如果我单击组合框
上的下拉箭头并单击我想要的项目,则会调用SelectedIndexChanged
- 很好。
如果我在组合框
的文本区域内单击并开始输入我想要选择的内容,然后按向上(或向下)键完成它,则调用SelectedIndexChanged
- 也不错。
如果我单击组合框
上的下拉箭头并开始输入我想要选择的内容并按 Enter 键完成,则不会调用 SelectedIndexChanged
- 问题。
在最后一种情况下是否有由 ENTER
引起的不同事件?我尝试过使用 TextChanged
和 TextUpdate
事件,但这些事件似乎不起作用:
Private Sub cmbStatus_TextChanged(sender As System.Object, e As System.EventArgs) Handles cmbStatus.TextChanged
If e.Equals(Keys.Enter) Then
Call SomeMethod()
End If
我应该使用除e.Equals(Keys.Enter)
之外的其他东西吗?
我还应该寻找其他事件吗?
编辑:
ComboBox
中的项目示例如下:
- 10 - 新条目和完整性检查
--->这是最常见的类型
- 13 - 分配给 TRB/HRB
---> 有一些带有“/”
- 60 - 外部(保留直至另行通知)
---> 有一些带有“(”和“)”
基本上,每个列表的类型都是“## - SOME TEXT”。
最佳答案
免责声明:这是用 C# 编写的 - 如果您需要将其翻译为 VB,请告诉我。
private void comboBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
//It's important to also check that the Combo Box is displaying its Drop Down. If
//you want this to execute even when it is not displayed, remove the check for
//comboBox1.DroppedDown.
if (e.KeyCode == Keys.Enter && comboBox1.DroppedDown &&
!string.IsNullOrEmpty(comboBox1.Text))
{
int index;
//Attempt to locate the string typed in by the user. An index of -1
//means it was not found.
if ((index = comboBox1.FindStringExact(comboBox1.Text)) != -1)
{
//Update the SelectedIndex.
comboBox1.SelectedIndex = index;
}
}
}
有趣的是,docs假设我们在处理用户所做的选择更改时应该使用 SelectionChangeCommited
事件而不是 SelectedIndexChanged
事件。在这种情况下,有必要这样做,因为使用我的方法会触发 SelectedIndexChanged
事件两次。
编辑:
为了防止用户必须键入整个字符串,请使用 Adi 答案中的建议:转到组合框的属性并将 AutoCompleteMode
设置为 SuggestAppend
和 AutoCompleteSource
到 ListItems
- 我在创建答案时实际上使用了这些设置,所以它应该适合您。
关于vb.net - Enter 时未调用 ComboBox 的 SelectedIndexChanged 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12750315/