首页 > 解决方案 > 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;
    }

标签: c#textboxlistboxkeydownkeyup

解决方案


您对事件名称感到困惑。
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;
}

推荐阅读