我试图这样做,当用户输入组合框时,组合框将尝试找到完全匹配搜索值的第一个项目。如果那不可能,它将尝试找到包含搜索值的第一个。如果前面提到的它都不会变成红色。现在我已经找到了这个部分并且正在工作,但我遇到的问题是,当用户尝试退格时,搜索将再次触发,因此它在大多数时间再次选择一行。如何在退格后不进行搜索,或者在用户尝试退格时阻止它选择索引。这是我使用的代码:
private void BestelIndexSearch(object sender, EventArgs e)
{
ComboBox Cmbbx = sender as ComboBox;
int index = -1;
string searchvalue = Cmbbx.Text;
if (Cmbbx.Text != "")
{
for (int i = 0; i < Cmbbx.Items.Count; i++)//foreach replacement (not possible with combobox)
{
//search for identical art
if (Cmbbx.Items[i].ToString().Equals(searchvalue))
{
index = Cmbbx.Items.IndexOf(searchvalue);
break;//stop searching if it's found
}
//search for first art that contains search value
else if (Cmbbx.Items[i].ToString().Contains(searchvalue) && index == -1)
{
index = Cmbbx.FindString(searchvalue);
break;//stop searching if it's found
}
}
}
//if nothing found set color red
if (index == -1)
{
Cmbbx.BackColor = Color.Red;
}
//if found set color white, select the item
else
{
Cmbbx.BackColor = Color.White;
Cmbbx.SelectedIndex = index;
}
//select text behind cursor
Cmbbx.SelectionStart = searchvalue.Length;
Cmbbx.SelectionLength = Cmbbx.Text.Length - searchvalue.Length;
}
代码设置为在TextChanged
事件上触发,并且绑定到多个组合框。如果有人可以帮助我,那就会受到影响。
答案 0 :(得分:0)
您应该在组合框中添加一个Keydown事件,以检查按下了哪个键并使用以下代码修改代码:
private bool _isCheckedActivated = true;
private void BestelIndexSearch(object sender, EventArgs e)
{
if (! _isCheckedActivated)
{
_isCheckedActivated = true;
return;
}
[...]
}
private void comboBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Back)
_isCheckedActivated = false;
}
答案 1 :(得分:0)
或者,您可以在自动填充功能中使用构建。使用内置功能,您不太容易出现错误,用户可以在选择项目之前预览备选方案。如果您有多个组合框,则可以创建扩展方法。
public static class MyExtensions
{
public static void SetDataAndAutoCompleteSource<T>(this ComboBox cmb, IEnumerable<T> src)
{
cmb.DataSource = src;
cmb.AutoCompleteSource = AutoCompleteSource.ListItems;
cmb.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
AutoCompleteStringCollection aSrc = new AutoCompleteStringCollection();
aSrc.AddRange(src.Select(c => c.ToString()).ToArray());
cmb.AutoCompleteCustomSource = aSrc;
}
}
用法:
comboBox1.SetDataAndAutoCompleteSource(myDataSource);