winform textbox 自动完成功能

DataTable table = DB.DbHelper.QueryByTable("select id,namefrom dept");
//用DataTable中的数据构建字符串数组   
ArrayList al = new ArrayList();
for (int i = 0; i < table.Rows.Count; i++)
{
     if (!al.Contains(table.Rows[i]["id"].ToString()))
     {
           al.Add(table.Rows[i]["id"].ToString() + " " + table.Rows[i]["name"].ToString());
     }
}
AutoCompleteStringCollection ac = new AutoCompleteStringCollection();
string[] s = (string[])al.ToArray(typeof(string));
 for (int i = 0; i < s.GetLength(0); i++)
{
      ac.Add(s[i]);
}
 this.txt_Name.AutoCompleteCustomSource = ac;//设置该文本框的自动完成数据源 

说明: textbox的相关属性需设置好

  this.txt_Name.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
  this.txt_Name.AutoCompleteSource = AutoCompleteSource.CustomSource;

posted @ 2011-08-15 12:46  徐文峰  阅读(1733)  评论(1编辑  收藏  举报