C#KeyUp和KeyDown文本框事件可控制列表框的选定项

时间:2019-07-07 17:44:21

标签: c# textbox listbox keydown keyup

我的表单中有一个文本框,我将其用作列表框的搜索栏。目前,我已设置文本框,以便在您使用以下代码键入时在列表框中主动选择一个项目:

    private void TextBox1_TextChanged(object sender, EventArgs e) 
    {
        var textBox = (TextBox)sender;
        listBox1.SelectedIndex = textBox.TextLength == 0 ?
            -1 : listBox1.FindString(textBox.Text);
    }

我想完成的就是能够同时使用向上和向下箭头键来调整选择的内容。例如,如果列表框包含两项:开始输入“ t”时,Test1和Test2将被选择。与必须完成键入“ 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;
    }

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

@Sohaib Jundi谢谢!!!这使事情变得难以置信!我最终稍稍调整了代码以修复发生的错误,以及一个光标所遇到的小错误,以防其他人遇到类似的错误。

   private void TextBox1_KeyUp(object sender, KeyEventArgs e)
    {
        int index = listBox1.SelectedIndex;
        int indexErrorFix = listBox1.Items.Count;
        if (e.KeyCode == Keys.Up)
        {
            index--;

        }
        else if (e.KeyCode == Keys.Down)
        {
            index++;

        }
        if (index < indexErrorFix && index >= 0)
        {
            listBox1.SelectedIndex = index;
        }
        else { }

        textBox1.SelectionStart = textBox1.Text.Length;
    }