我的表单中有一个文本框,我用作我的列表框的搜索栏。当前,我已经设置了文本框,可以在使用以下代码输入时在列表框中积极选择一个项目:
private void TextBox1_TextChanged(object sender, EventArgs e)
{
var textBox = (TextBox)sender;
listBox1.SelectedIndex = textBox.TextLength == 0 ?
-1 : listBox1.FindString(textBox.Text);
}
我想完成的是能够使用UP&向下箭头键调整所选内容。例如,如果列表框包含两个项目: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;
}
您对事件名称感到困惑。
键和键是指向上和向下按下键盘按钮,而不是按下上下箭头。要做您要寻找的事情,您将需要其中一个,例如:键,如下:
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;
}
@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;
}