【发布时间】:2018-06-05 13:38:52
【问题描述】:
我有一个 C# Winform 应用程序。它有一个ComboBox。我的目标是在输入delete 键时,让ComboBox 下拉列表中选择的项目出现在ComboBox 的可编辑部分中。例如,如果ComboBox 有项目A,B。和C,然后在加载Form 时显示项目A。如果我单击下拉菜单,将鼠标悬停在项目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;
}
}
}
}
【问题讨论】:
-
您是否已验证
comboBox.FindStringExact(selectedItemText);会返回您所期望的结果? -
@JuanR:
As it is, I've verified that I am getting the selected item text -
这不是我问的。我问
FindStringExact的返回值是多少。 -
@JuanR:我很抱歉。是的,
comboBox.FindStringExact(selectedItemText);返回与selectedItemText对应的索引 -
设置
comboBox.DroppedDown = false;而不是聚焦窗口。然后设置comboBox.SelectedItem = selectedItemText;
标签: c# winforms combobox keydown