Winforms - 自动完成TextBox不显示结果

时间:2015-08-17 16:13:01

标签: 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;
    }

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

2 个答案:

答案 0 :(得分:1)

你不应该试图自己实施它;工作已经完成。删除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;
        }

答案 1 :(得分:-1)

您是否尝试在设置AutoCompleteCustomSource属性后调用Application.DoEvents? Use of Application.DoEvents()