想实现自动完成,就必须明白三个属性:
AutoCompleteSource属性: 设置自动完成的来源。此属性的值为AutoCompleteSource枚举值之一
AutoCompleteMode属性:设置自动完成的显示模式。此属性的值为AutoCompleteMode枚举值之一
AutoCompleteCustomSource属性:自定义完成来源。当AutoCompleteSource属性值为CustomSource时,此
属性才起做用。属性值为AutoCompleteStringCollection集合对象,可以通过AutoCompleteCustomSource属性
这个集合。
可以通过直接属性值来实现自动完成,也可以用代码实现,用代码如下:
VB.NET Code:
Dim arrStr(5) As String
arrStr(0) = "123"
arrStr(1) = "123456"
arrStr(2) = "123789"
arrStr(3) = "123345"
arrStr(4) = "123478"
arrStr(5) = "123567"
Dim AutoSource As New AutoCompleteStringCollection()
AutoSource.AddRange(arrStr)
txtAuto.AutoCompleteMode = AutoCompleteMode.SuggestAppend
txtAuto.AutoCompleteSource = AutoCompleteSource.CustomSource
txtAuto.AutoCompleteCustomSource = AutoSource
C#
myCutomSource.AddRange( new string []{ " 成都市东门 " , " 成都市北门 " , " 成都市西门 " , " 成都市南门 " });
this .textBox5.AutoCompleteSource = AutoCompleteSource.CustomSource;
this .textBox5.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
this .textBox5.AutoCompleteCustomSource = myCutomSource;
在数据库中读取:
//这样试试,我没调试,可能会报错,自己该该就行了
AutoCompleteStringCollection cs = new AutoCompleteStringCollection();//全局变量
//窗体的load事件写
private void Form5_Load(object sender, EventArgs e)
{
this.txtSelect.AutoCompleteMode = AutoCompleteMode.Suggest;
this.txtSelect.AutoCompleteSource = AutoCompleteSource.CustomSource;
this.txtSelect.AutoCompleteCustomSource = cs;
}
//文本改变事件
private void txtSelect_TextChanged(object sender, EventArgs e)
{
cs.Clear();
DataTable tab1 = sqldataset( "select CompanyName from Customers where CompanyName like '% " + txtSelect.Text.Trim() + "% ' ").Tables[0];
for (int i = 0; i < tab1.Rows.Count; i++)
{
cs.Add(tab1.Rows[i][ "CompanyName "].ToString().Trim());
}
}
private System.Data.DataSet sqldataset(string str)
{
System.Data.SqlClient.SqlConnection conn = new SqlConnection( "server = .; uid = sa; pwd = ; database = NorthWind ");
System.Data.SqlClient.SqlDataAdapter getdata;
if (conn.State.ToString() == "Closed ")
conn.Open();
getdata = new SqlDataAdapter(str.Trim(), conn);
System.Data.DataSet sj = new System.Data.DataSet();
getdata.Fill(sj, "sj ");
getdata.Dispose();
return sj;
}