c# - C# KeyUp & KeyDown 文本框事件来控制列表框的选中项
问题描述
我的表单中有一个文本框,用作列表框的搜索栏。目前,我将文本框设置为在您使用以下代码键入时主动选择列表框中的项目:
private void TextBox1_TextChanged(object sender, EventArgs e)
{
var textBox = (TextBox)sender;
listBox1.SelectedIndex = textBox.TextLength == 0 ?
-1 : listBox1.FindString(textBox.Text);
}
我想要完成的是能够使用向上和向下箭头键来调整选择的内容。例如,如果列表框包含两个项目:Test1 和 Test2,当您开始键入“t”时 test1 将被选中。与必须完成键入“test2”来更改选择的内容相反,我希望能够键入“t”,然后按向下箭头键选择 test2,但将焦点保持在文本框中。
我尝试使用以下内容,但是当按下向上或向下箭头键时,文本框中的光标会调整而不是 selectedIndex
private void TextBox1_KeyUp(object sender, KeyEventArgs e)
{
int index = listBox1.SelectedIndex;
index = index--;
listBox1.SelectedIndex = index;
}
private void TextBox1_KeyDown(object sender, KeyEventArgs e)
{
int index = listBox1.SelectedIndex;
index = index++;
listBox1.SelectedIndex = index;
}
解决方案
您对事件名称感到困惑。
KeyUp 和 KeyDown 是指上下按键盘按钮,而不是按上下箭头。要执行您正在寻找的内容,您将需要其中之一,例如: KeyUp 如下所示:
private void TextBox1_KeyUp(object sender, KeyEventArgs e)
{
int index = listBox1.SelectedIndex;
if(e.KeyCode == Keys.Up)
{
index--;
}
else if(e.KeyCode == Keys.Down)
{
index++;
}
listBox1.SelectedIndex = index;
}
推荐阅读
- macos - 在 PC 中未检测到 Beaglebone black
- python - 如何获取写入文本文件的函数?
- sql - 使用标准 sql,如何将时间戳转换为 unix 时间?
- pandas - Pandas Dataframe Apply - 附加到列表的 lambda 函数
- python-3.x - 在 Tkinter 中查看需要用户输入的功能并与之交互
- salesforce - 前 4 个字符的模式匹配 SOQL?
- git - 如何删除分支名称中带有奇怪字符的本地 git 分支
- vim - Vim 状态行分隔 (%=) 与 Unicode 字符
- php - 复选框到 php 数据库
- rust - 在 Rust 的外部函数中使用指向指针的指针的正确方法是什么?