根据 C# 中的文本框条目显示列表框项
本文关键字:显示 列表 根据 文本 | 更新日期: 2023-09-27 17:57:00
我只想问一下,一旦用户开始在文本框中键入内容,是否可以开始在列表框中显示选项(对于在文本框中输入的文本)?
谢谢。
可能,您正在寻找这样的东西:
- 在表格上
ListBox
(myListBox
) - 放入
TextBox
(myTextBox
在下面的实现中) - 为文本框实现
TextChanged
事件处理程序
可能的实现
// When TextBox's Text changed
private void myTextBox_TextChanged(object sender, EventArgs e) {
string textToFind = (sender as Control).Text;
// Do all the changes in one go in order to prevent re-drawing (and blinking)
myListBox.BeginUpdate();
try {
myListBox.SelectedIndices.Clear();
// We don't want selecting anything on empty
if (string.IsNullOrEmpty(textToFind))
return;
for (int i = 0; i < myListBox.Items.Count; ++i) {
string actual = myListBox.Items[i].ToString();
// Now we should compare two strings; there're many ways to do this
// as an example let's select the item(s) which start(s) from the text entered,
// case insensitive
if (actual.StartsWith(textToFind, StringComparison.InvariantCultureIgnoreCase)) {
myListBox.SelectedIndices.Add(i);
// can we select more than one item == shall we proceed?
if (myListBox.SelectionMode == SelectionMode.One)
break;
}
}
}
finally {
myListBox.EndUpdate();
}
}