TextBox的AutoCompleteSource和AutoCompleteMode属性允许我在文本框中使用自动完成功能。
我直接绑定了一个数据表作为文本框的AutoCompleteSource,它运行良好。
在某些情况下输入词在源中不可用,自动完成没有结果,因此,我需要在这些情况下做其他事情。
我应该如何检查自动完成结果是否为空?
答案 0 :(得分:1)
您可以采取以下一种方法。当输入的字符超过3个时,以下代码将在文本框的TextChanged
事件中获得建议。我们去获取建议,然后检查是否有任何建议被返回。如果是,我们设置AutoCompleteCustomSource
。否则,我们会做点什么 - 无论我们想做什么。
private void textBox1_TextChanged(object sender, EventArgs e)
{
TextBox t = sender as TextBox;
if (t != null)
{
// Here I am making the assumption we will get suggestions after
// 3 characters are entered
if (t.Text.Length >= 3)
{
// This will get the suggestions from some place like db,
// table etc.
string[] arr = GetSuggestions(t.Text);
if (arr.Length == 0) {// do whatever you want to}
else
{
var collection = new AutoCompleteStringCollection();
collection.AddRange(arr);
this.textBox1.AutoCompleteCustomSource = collection;
}
}
}
}