簡體   English   中英

Winforms - 自動完成TextBox不顯示結果

[英]Winforms - AutoComplete TextBox doesn't show results

我試圖在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;
        }

您是否嘗試在設置AutoCompleteCustomSource屬性后調用Application.DoEvents? 使用Application.DoEvents()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM