文本框(Textbox)和下拉框(Combobox)自动联想功能的实现

看见一大侠介绍这种联想的效果,很棒!

怎样使自己程序中的文本框或下拉框具有像百度和Google那样的自动联想功能?微软的TextBox和Combobox控件为我们提供了简便方法。

首先需要学习TextBox(或Combobox)的两个属性,一个属性是AutoCompleteMode,指定控件中使用的自动完成功能的模式,有四种模式,分别是:

None:禁用控件的自动完成功能                           

Suggest:显示与编辑控件关联的辅助下拉列表。此下拉列表填充了一个或多个建议完成字符串。显示效果如下:      

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

 

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

  

我们一般常用SuggestAppend模式。

另一个属性为AutoCompleteSource,指定了控件实现自动联想功能的数据源,读者可以自己去查看MSDN,这里就不再赘述。下面是一个代码示例:

首先设置TextBox和Combobox的AutoCompleteSource的属性为CustomSource,然后设置TextBox和Combobox的AutoCompleteMode属性为SuggestAppend。

 

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Data.Common;



namespace 文本框联想功能的实现

{

    public partial class Form1 : Form

    {

        DataTable dt = new DataTable();

        public Form1()

        {

            InitializeComponent();

        }



        private void Form1_Load(object sender, EventArgs e)

        {

            InitialAutoCompleteList();

        }



        private void InitialAutoCompleteList()

        {

            string []array=new string[]{"hello","hi","nihao","hehe","yes","no","nobody","morning","yellow","moon"};

            DataColumn  dc=new DataColumn("name");

            this.dt.Columns.Add(dc);

            for (int i = 0; i < 10;i++ )

            {

                DataRow dr = dt.NewRow();

                dr[0] = array[i];

                dt.Rows.Add(dr);

            }

            AutoCompleteStringCollection AutoCollection = new AutoCompleteStringCollection();

            foreach (DataRow dr in dt.Rows)

            {

                AutoCollection.Add(dr["name"].ToString());

            }

            this.textBox_TestAutoComplete.AutoCompleteCustomSource = AutoCollection;

            this.comboBox_TestAutoComplete.AutoCompleteCustomSource = AutoCollection;

        }

    }

}

下载:WindowsFormsApplication1.zip

你可能感兴趣的:(combobox)