1

I'm looking fr a good example of a WinForm Autocomplete textbox that goes to the database for a list of matching items much like Google's AutoSuggest search text box does.

For example, if the user types really fast we need not submit one database search for each keystoke, however, after retriving results, if the user has queued up additional keystokes that have not been searched, do another search.

Update:

For example,

I've never done multi -thread before in a WinForm app but I thought I would start up a new thread every time the contents of the Search Text box changed and I would query the database for matches. If the textbox changed by the time I got the results back, I would disregard the query results.

However, I am getting this error:

Cross-thread operation not valid: Control accessed from a thread other than the thread it was created o

Here's my code:

 private void txtSearch_TextChanged(object sender, EventArgs e)
        {

            Thread newThread = new Thread(BeginSourceThread);
            newThread.Start(txtSearch.Text);
        }

        private void BeginSourceThread(object value)
        {

            string searchText = (string)value;

            AutoCompleteStringCollection autoCompleteItems = new AutoCompleteStringCollection();

            DataSet ds = MetaData.GetMatchingDatabaseObjects(txtSearch.Text, sqlConnectionStringBuilder.ConnectionString);
            DataTable dtbObjects = ds.Tables[0];

            if (txtSearch.Text != searchText)
            {
                return;
            }

            foreach (DataRow row in dtbObjects.Rows)
            {
                autoCompleteItems.Add(row["ObjectName"].ToString());
            }

            txtSearch.AutoCompleteCustomSource = autoCompleteItems;
            System.Diagnostics.Debug.WriteLine("Done Returning " + autoCompleteItems.Count.ToString() + " items.");

      }

}

4

3 回答 3

0

如果相关,请在Reactive Extensions的典型示例中自动建议:

于 2012-08-20T15:06:17.037 回答
0

将该txtSearch.AutoCompleteCustomSource = autoCompleteItems行放在Invoke调用中,以确保您仅在主 UI 线程内修改 GUI:

Action<AutoCompleteStringCollection> action = items => txtSearch.AutoCompleteCustomSource = items;
Invoke(action, autoCompleteItems);
于 2012-08-20T13:00:37.097 回答
0

以下是使用 Key_Down 事件刷新结果的方法:

http://www.codeproject.com/Articles/243368/AutoComplete-Textbox

于 2012-08-20T05:43:02.407 回答