我正在尝试在 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;
}
关于c# - Winforms - 自动完成文本框不显示结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32055059/