首先需要学习TextBox(或Combobox)的两个属性,一个属性是AutoCompleteMode,指定控件中使用的自动完成功能的模式,有四种模式,分别是:
None:禁用控件的自动完成功能
Suggest:显示与编辑控件关联的辅助下拉列表。此下拉列表填充了一个或多个建议完成字符串。显示效果如下:


Append:将最可能的候选字符串的其余部分追加到现有的字符,并突出显示追加的字符。显示效果如下:

SuggestAppend:同时应用 Suggest 和 Append选项。显示效果如下:

我们一般常用SuggestAppend模式。
另一个属性为AutoCompleteSource,指定了控件实现自动联想功能的数据源,读者可以自己去查看MSDN,这里就不再赘述。下面是一个代码示例:
首先设置TextBox和Combobox的AutoCompleteSource的属性为CustomSource,然后设置TextBox和Combobox的AutoCompleteMode属性为SuggestAppend。
private void IniComboxPname()
{
try
{
string sql = string.Format("select * from tb_product ");//where pName like '{0}%' , pname
AutoCompleteStringCollection AutoCollection = new AutoCompleteStringCollection();
using (MySqlDataReader dr = helperMySql.getmysqlread(sql))
{
while (dr.Read())
{
try
{
AutoCollection.Add(dr.GetString(2).ToString());
}
catch (Exception exx)
{
// MessageBox.Show(exx.ToString() + dr.GetString(1) + dr.GetString(2));
}
}
}
this.comboBoxPname.AutoCompleteCustomSource = AutoCollection;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void FormMain_Load (object sender, EventArgs e)
{
IniComboxPname();
}
网友评论