【问题标题】:C# Create Custom Autocomplete TextBoxC# 创建自定义自动完成文本框
【发布时间】:2012-01-06 18:59:47
【问题描述】:

我想创建一个文本框,其中会显示自动完成下拉菜单并提供一些建议。
当然,我想过在我的文本框上使用 AutoCompleteCustomSource,但问题是,文本框会自动过滤所有不包含输入文本的内容。

例如,如果我输入“listen”,我的算法会将“listen (now)”、“listen (later)”和“listen to AAA”作为建议。当我将它们放入 autocompletecustomsource 时,一切正常。但是一旦我写“现在”,文本变成“现在听”,自动完成下拉菜单是空的,因为 autocompletecustomsource 中没有任何项目以“现在听”开头。

接下来我尝试将输入从文本框更改为组合框,我将我的建议放在 Items 属性中,然后以编程方式打开下拉列表。这里的问题是,当我从代码中打开下拉菜单时,会自动选择第一个项目,并且第一个项目的文本会替换输入的文本。

想象第一个示例:当您键入“listen”时,下拉菜单打开,其中包含“listen (now)”、“listen (later)”和“listen to AAA”项目。但是组合框中的文本会自动更改为第一项,因此变为“听(现在)”,您无法输入其他任何内容。

这是我目前正在使用的代码:

    private void comboBox2_KeyUp(object sender, KeyEventArgs e)
    {
        string asd = comboBox2.Text;
        if (asd.Length < 3)
            return;

        if (e.KeyCode == Keys.Enter)
        {
            OpenItem(asd);
            return;
        }
        if (AllToString(comboBox2.Items).Contains(asd))
        {
            return;
        }

        DateTime started = DateTime.Now;
        System.Threading.Thread tth = new System.Threading.Thread((System.Threading.ThreadStart)delegate()
            {
                JsonData dat = new JsonData();
                //Query autocomplete
                ...
                //End Query
                comboBox2.Invoke((MethodInvoker)delegate()
                {
                    if (comboBox2.Tag == null || ((DateTime)comboBox2.Tag) < started)
                    {
                        comboBox2.Items.Clear();
                        comboBox2.Items.AddRange(li.ToArray()); //li is the list of suggestions
                        comboBox2.Select(comboBox2.Text.Length, 0);
                        comboBox2.Tag = started;
                        if (li.Count != 0)
                            comboBox2.DroppedDown = true;
                        else
                        {
                            comboBox2.Focus();
                            comboBox2.Select(comboBox2.Text.Length, 0);
                        }
                    }
                });
            });
        tth.IsBackground = false; tth.Start();
    }

所以我的问题是:我如何创建一个文本或组合框,我可以在其中将我的建议放在下拉列表中,而不更改输入的文本并且不进行过滤。我希望一直显示所有建议。

感谢您的帮助,亚历克斯

【问题讨论】:

  • 使用文本框,尝试检索始终相同的建议列表,而不用用户输入过滤它们。

标签: c# .net winforms autocomplete custom-controls


【解决方案1】:

更好的是创建一个继承组合框并覆盖事件的新类

   public class myCombo : ComboBox
    {
        protected override void OnPaint(PaintEventArgs e)
        {


            base.OnPaint(e);
        }
    }

我做了一些改变显示的事情.. 放置一个网格,但这是很久以前的事了。

尝试搜索这个。

【讨论】:

    猜你喜欢
    • 2017-09-01
    • 2016-01-20
    • 1970-01-01
    • 2020-05-17
    • 1970-01-01
    • 2019-08-05
    • 1970-01-01
    • 2012-12-21
    • 2017-05-19
    相关资源
    最近更新 更多