我有一个C#Winform应用程序。它有一个ComboBox
。我的目标是在输入ComboBox
键时,ComboBox
下拉列表中选中的项目会显示在delete
的可编辑部分中。例如,如果ComboBox
包含商品A
,B
。和C
,然后在加载A
时显示项Form
。如果我点击下拉菜单,将鼠标悬停在项C
上,然后输入delete
键,我希望下拉列表被删除,C
出现在该项目的可编辑部分ComboBox
。
实际上,我已经确认我收到了所选的项目文字,但代码行comboBox.SelectedIndex = comboBox.FindStringExact(selectedItemText);
并未更改ComboBox
的可编辑部分中显示的内容
MCVE:
注意:表单有一个名为combobox
的组合框和一个名为textbox
的文本框
using System.Collections;
using System.Collections.Specialized;
using System.Windows.Forms;
namespace Winforms_Scratch
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//using string collection because I need to simulate what is returned from an Application Settings list
StringCollection computerList = new StringCollection { "C", "B", "A" };
ArrayList.Adapter(computerList).Sort();
comboBox.DataSource = computerList;
comboBox.KeyDown += ComboBox_KeyDown;
computerList = null;
}
private void ComboBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete && comboBox.DroppedDown)
{
ComboBox comboBox = (ComboBox)sender;
//get the text of the item in the dropdown that was selected when the Delete key was pressed
string selectedItemText = comboBox.GetItemText(comboBox.SelectedItem);
//take focus away from the combobox to force it to dismiss the dropdown
this.Focus();
//load selectedItemText into the textbox just so we can verify what it is
textBox.Text = selectedItemText;
//set the comboBox SelectedIndex to the index of the item that matches the
//text of the item in the dropdown that was selected when the Delete key was pressed
comboBox.SelectedIndex = comboBox.FindStringExact(selectedItemText);
comboBox.Refresh();
//Stop all further processing
e.Handled = true;
}
else if (e.KeyCode == Keys.Down && !comboBox.DroppedDown)
{
//If the down arrow is pressed show the dropdown list from the combobox
comboBox.DroppedDown = true;
}
}
}
}
答案 0 :(得分:1)
我的猜测是,组合框失去焦点后表现不同。在任何情况下,根据我对您的要求的理解,我做了以下更改并且它有效。您可以在设置所选项目后调用this.Focus()
,如果有单独的要求将焦点返回到窗口。您的SelectedIndex / FindStringExact方法与将SelectedItem设置为字符串的工作方式相同。
我摆脱了文本框,因为我理解它仅用于调试目的。
private void ComboBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete && comboBox.DroppedDown)
{
ComboBox comboBox = (ComboBox)sender;
// Get the text of the item in the dropdown that was selected when the
// Delete key was pressed
string selectedItemText = comboBox.GetItemText(comboBox.SelectedItem);
comboBox.DroppedDown = false;
comboBox.SelectedItem = selectedItemText;
//Stop all further processing
e.Handled = true;
}
else if (e.KeyCode == Keys.Down && !comboBox.DroppedDown)
{
// If the down arrow is pressed show the dropdown list from the combobox
comboBox.DroppedDown = true;
}
}