C# GUI跨线程问题/寻找WinForm TextBox在从数据库键入时自动完成的好例子
我正在寻找WinForm Autocomplete文本框的一个很好的例子,该文本框进入数据库查找匹配项的列表,就像Google的AutoSuggest搜索文本框一样 例如,如果用户键入的密钥非常快,那么我们不需要为每个密钥库提交一次数据库搜索,但是,在检索结果之后,如果用户已将尚未搜索的其他密钥库排队,则执行另一次搜索 更新: 比如说, 我以前从未在WinForm应用程序中执行过多线程,但我认为每次搜索文本框的内容发生更改时,我都会启动一个新线程,并查询数据库中的匹配项。如果在我返回结果时文本框发生了变化,我将忽略查询结果 但是,我遇到了以下错误:C# GUI跨线程问题/寻找WinForm TextBox在从数据库键入时自动完成的好例子,c#,winforms,C#,Winforms,我正在寻找WinForm Autocomplete文本框的一个很好的例子,该文本框进入数据库查找匹配项的列表,就像Google的AutoSuggest搜索文本框一样 例如,如果用户键入的密钥非常快,那么我们不需要为每个密钥库提交一次数据库搜索,但是,在检索结果之后,如果用户已将尚未搜索的其他密钥库排队,则执行另一次搜索 更新: 比如说, 我以前从未在WinForm应用程序中执行过多线程,但我认为每次搜索文本框的内容发生更改时,我都会启动一个新线程,并查询数据库中的匹配项。如果在我返回结果时文本框
Cross-thread operation not valid: Control accessed from a thread other than the thread it was created o
这是我的密码:
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.");
}
}以下是如何使用按键向下事件刷新结果:
将
txtSearch.AutoCompleteCustomSource=autoCompleteItems
行放入调用中,以确保仅在主UI线程中修改GUI:
Action<AutoCompleteStringCollection> action = items => txtSearch.AutoCompleteCustomSource = items;
Invoke(action, autoCompleteItems);
Action-Action=items=>txtSearch.AutoCompleteCustomSource=items;
调用(操作、自动完成项);
如果相关,请在以下典型示例中自动建议:
- (见练习5)
- (autosuggest是现场演示之一)