3

I am trying to implement search suggestions in WinForm. I placed a TextBox on the form; set AutoCompleteMode as SuggestAppend; AutoCompleteSource as CustomSource;

I have implemented TextChanged on the textbox to fetch results and add to AutoCompleteCustomeSource property. If I debug, I could see the results in this property but UI is not showing up any results. My code is here:

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;
    }

Can anyone please throw some light on this? Thanks

techspider
  • 3,370
  • 13
  • 37
  • 61

2 Answers2

1

You shouldn't be trying to implement it yourself; the work is done already. Remove this entire handler for TextChanged and start fresh; all you need to do is set the AutoCompleteCustomSource and it'll take care of the rest.

Change the signature for MyMethodFetchesResults to take no parameters, and then call this method from Load() or wherever you're initializing your form:

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

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

            txtSearchKey.AutoCompleteCustomSource = s;
        }
DrewJordan
  • 5,266
  • 1
  • 25
  • 39
-1

have you tried to call Application.DoEvents after setting the AutoCompleteCustomSource property?? Use of Application.DoEvents()

Community
  • 1
  • 1
Marco BFV
  • 100
  • 2
  • 14
  • Yes, this results in an error "Attempted to read or write protected memory. This is often an indication that other memory is corrupt." – techspider Aug 17 '15 at 16:47
  • I went with a work around. I implemented a ListBox below my TextBox and handling show/hide of the control along with populating results into the listbox. I kind of replicated the bahavior with listbox. – techspider Aug 25 '15 at 18:19