关于c#:在组合框中搜索值(使用退格键)

Search for value in combobox (use of backspace)

我试图做到这一点,以便当用户在组合框中键入内容时,组合框将尝试查找与搜索值完全匹配的第一项。 如果那不可能,它将尝试查找包含搜索值的第一个。 如果以上都不是,它将变成红色。 现在,我已经弄清楚了那部分内容并可以正常工作,但是我遇到的问题是,当用户尝试退格时,搜索将再次触发,因此它通常会再次选择一行。 如何使它不会在退格后搜索,或者如果用户尝试退格,则阻止它选择索引。 这是我使用的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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事件上触发,并且已绑定到多个组合框。 如果有人可以帮助我,那将是可取的。


或者,您可以使用自动完成功能中的buildt。 使用内置功能,您不容易出现错误,用户可以在选择项目之前预览替代方案。 如果您有多个组合框,则可以创建扩展方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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;
    }

}

用法:

1
comboBox1.SetDataAndAutoCompleteSource(myDataSource);

您应该在组合框中添加一个Keydown事件,以检查按下了哪个键,并使用以下内容修改代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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;
}