我有一个 C# WinForms 应用程序,我通过编写其项目的任何部分并在输入文本部分后按 Enter 键成功过滤了 ComboBox 项目,使用以下代码:
private void detailsGridView_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
var comboBox = e.Control as ComboBox;
if (comboBox != null)
{
comboBox.DropDownStyle = ComboBoxStyle.DropDown;
comboBox.PreviewKeyDown += ComboBox_PreviewKeyDown;
}
}
private void ComboBox_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if ((e.KeyCode & e.KeyData) == Keys.Return)
{
if (((ComboBox)sender).SelectedItem == null)
{
e.IsInputKey = true;
((ComboBox)sender).DataSource = accounts
.Where(a => a.Name.Contains(((ComboBox)sender).Text))
.ToList();
((ComboBox)sender).DroppedDown = true;
}
}
}
然后我在 ((ComboBox)sender).DroppedDown = true 行中遇到了问题,其中列表被删除并立即关闭。
我在调试时注意到 KeyDown 事件引发了两次,因此我尝试使用标志变量来检查第二次引发并取消,但没有用。 我尝试了许多其他方法,例如:
但是列表出现后仍然立即关闭。
在这种情况下正确的做法是什么?
编辑:
我注意到当我删除条件行时 if ((e.KeyCode & e.KeyData) == Keys.Return)
该功能无法正常工作,但下拉列表仍保持打开状态。
我通过添加一个单独的方法来处理过滤器和另一个处理KeyDown问题的方法解决了这个问题,这是代码:
private void detailsGridView_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control is ComboBox comboBox)
{
comboBox.DropDownStyle = ComboBoxStyle.DropDown;
comboBox.KeyDown += ComboBox_KeyDown;
comboBox.PreviewKeyDown += ComboBox_PreviewKeyDown;
}
}
private void ComboBox_PreviewKeyDown(object sender,
PreviewKeyDownEventArgs e)
{
if ((e.KeyCode & e.KeyData) == Keys.Enter)
if (((ComboBox)sender).SelectedItem == null)
e.IsInputKey = true;
}
private void ComboBox_KeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyCode & e.KeyData) == Keys.Enter)
{
if (((ComboBox)sender).SelectedItem == null)
{
e.SuppressKeyPress = e.Handled = true;
((ComboBox)sender).DataSource = accounts
.Where(a => a.Name.Contains(((ComboBox)sender).Text))
.ToList();
((ComboBox)sender).DroppedDown = true;
}
}
}
任何人都可以轻松测试它,它对任何项目都有效。