【发布时间】:2016-03-31 22:49:15
【问题描述】:
我想做的是在 ComboBox 中搜索一个单词,或者像这样的单词的一部分:
例如,我的组合框中有这些条目:
abc
Abc
Dabc
adbdcd
当我搜索“abc”时,它应该会显示列表中的每个人,除了“
adbdcd"
我从 mysql 数据库中填充我的组合框,所以我的项目位于“Collection”中。
我启用了自动完成功能(模式:SuggestAppend,来源:ListItems)
这是代码,我现在正在使用:
private void comboBox1_KeyPress(object sender, KeyPressEventArgs e) { 组合键按下(); }
private void comboBox1_TextChanged(object sender, EventArgs e)
{
if (comboBox1.Text.Length == 0) comboKeyPressed();
}
private void comboKeyPressed()
{
comboBox1.DroppedDown = true;
object[] originalList = (object[])comboBox1.Tag;
if (originalList == null)
{
// backup original list
originalList = new object[comboBox1.Items.Count];
comboBox1.Items.CopyTo(originalList, 0);
comboBox1.Tag = originalList;
}
// prepare list of matching items
string s = comboBox1.Text.ToLower();
IEnumerable<object> newList = originalList;
if (s.Length > 0)
{
newList = originalList.Where(item => item.ToString().ToLower().Contains(s));
}
// clear list (loop through it, otherwise the cursor would move to the beginning of the textbox...)
while (comboBox1.Items.Count > 0)
{
comboBox1.Items.RemoveAt(0);
}
// re-set list
comboBox1.Items.AddRange(newList.ToArray());
}
这段代码的问题是,如果我在示例列表中搜索“abc”,“adbdcd”也会出现。当我在组合框中按退格键时,此代码会随机使我的程序崩溃。
【问题讨论】:
-
在 text_Changed 事件中这个检查有什么用? comboBox1.Text.Length == 0 或者是 !=0 ?
标签: c# combobox autocomplete