c# - Winforms - 自动完成文本框不显示结果

标签 c# winforms

我正在尝试在 WinForm 中实现搜索建议。我在表单上放置了一个 TextBox;将 AutoCompleteMode 设置为 SuggestAppend; AutoCompleteSource 作为 CustomSource;

我已经在文本框上实现了 TextChanged 以获取结果并添加到 AutoCompleteCustomeSource 属性。如果我调试,我可以在此属性中看到结果,但 UI 未显示任何结果。我的代码在这里:

private void txtSearchKey_TextChanged(object sender, EventArgs e)
    {
        AutoCompleteStringCollection searchSuggestions = new AutoCompleteStringCollection();
        // Clear current source without calling Clear()
        for (int i = 0; i < txtSearchKey.AutoCompleteCustomSource.Count; i++)
            txtSearchKey.AutoCompleteCustomSource.RemoveAt(0);

        if (txtSearchKey.Text.Length >= 3)
        {
            var filteredSearchText = String.Join(",", txtSearchKey.Text.Split(' ').Where(x => x.Length > 2));

            //The below method retrieves the DataTable of results
            var searchResults = MyMethodFetchesResults(filteredSearchText);

            if (searchResults.Rows.Count == 0)
            {
                searchSuggestions.Add("No result found");
            }
            else
            {
                foreach (DataRow searchResult in searchResults.Rows)
                    searchSuggestions.Add(searchResult["Name"].ToString());
            }
        }

        txtSearchKey.AutoCompleteCustomSource = searchSuggestions;
    }

任何人都可以对此有所了解吗?谢谢

最佳答案

您不应该尝试自己实现它;工作已经完成了。删除 TextChanged 的整个处理程序并重新开始;您需要做的就是设置 AutoCompleteCustomSource,它会处理剩下的事情。

MyMethodFetchesResults 的签名更改为不带参数,然后从 Load() 或您初始化表单的任何位置调用此方法:

private void LoadAutoCompleteList()
        {
            DataTable d = MyMethodFetchesResults();
            AutoCompleteStringCollection s = new AutoCompleteStringCollection();

            foreach (DataRow row in d.Rows)
            {
                s.Add(row[1].ToString());
            }

            txtSearchKey.AutoCompleteCustomSource = s;
        }

关于c# - Winforms - 自动完成文本框不显示结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32055059/

相关文章:

c# - JSON 和 XML 的独立 Web 服务?

c# - 打开多个文件(OpenFileDialog,C#)

windows - 网络摄像头,视频源对话框出现

c# - 我应该在 C# 中为我的项目使用 WPF 还是 Windows 窗体应用程序?

c# - 关于C#自动实现属性的问题

javascript - 从 Node.js 服务器读取数据时 PHP file_get_contents 命令不起作用

c# - 自定义(派生)List<T>

c# - 使用 P/Invoke 导致系统 AccessViolationException

c# - 带状状态标签中的倒数计时器 c#

c# - 如何以编程方式检查电脑上是否存在 MS Excel?