TextBox控件本身是提供了一个自动提示功能,只要用上这三个属性:
autoCompleteCustomSource:autoCompleteSource 属性设置为CustomSource 时要使用的 StringCollection。
autoCompleteMode:指示文本框的文本完成行为。
autoCompleteSource:自动完成源,可以是 autoCompleteSource 的枚举值之一。
就行了, 一个简单的示例如下
复制代码 代码如下:
textBox1.autoCompleteCustomSource .AddRange(new string[] { "java","JavaScript","Js","c#","c","c++" });
textBox1.autoCompleteMode = autoCompleteMode.SuggestAppend;
textBox1.autoCompleteSource = autoCompleteSource.CustomSource;
可是这种方式的不支持我们中文的简拼自动完成(如在文本框里输入"gz"就会出现"广州")。只好自己写一个支持简拼自动完成的控件了。
这是效果图
复制代码 代码如下:
private TextBox _tb;
private ListBox _lb;
private Datatable _dt_datasource;
private bool _text_lock;
private string _general_text;//原始输入文本框的值
private bool _lb_kd_first_top;//ListBox是否第一次到达顶部
private int _itemCount;
复制代码 代码如下:
/// <summary>
/// TextBox的Text属性,增加了_text_lock *** 作,放置触发TextChanged事件
/// </summary>
private string TextBoxText
{
get { return _tb.Text; }
set
{
_text_lock = true;
_tb.Text = value;
_text_lock = false;
}
}
/// <summary>
/// 显示在ListBox的字段名
/// </summary>
public string Valuename { get; set; }
/// <summary>
/// 用于匹配的字段名
/// </summary>
public string Codename { get; set; }
/// <summary>
/// 显示提示项的数量
/// </summary>
public int ItemCount
{
get
{ return _itemCount; }
set
{
if (value <= 0)
_itemCount = 1;
else
_itemCount = value;
}
}
public Datatable DataSource
{
get { return _dt_datasource; }
set { _dt_datasource = value; }
}
复制代码 代码如下:
public autoComplete()
{
InitialControls();
}
复制代码 代码如下:
voID autoComplete_Load(object sender,EventArgs e)
{
_tb.WIDth = this.WIDth;
_lb.WIDth = _tb.WIDth;
this.Height = _tb.Height-1;
}
voID autoComplete_LostFocus(object sender,EventArgs e)
{
_lb.Visible = false;
this.Height = _tb.Height-1;
}
复制代码 代码如下:
//列表框按键事件
voID _lb_KeyDown(object sender,KeyEventArgs e)
{
if (_lb.Items.Count == 0 || !_lb.Visible) return;
if (!_lb_kd_first_top && ((e.KeyCode == Keys.Up && _lb.Selectedindex == 0) || (e.KeyCode == Keys.Down && _lb.Selectedindex == _lb.Items.Count)))
{
_lb.Selectedindex = -1;
TextBoxText = _general_text;
}
else
{
TextBoxText = ((DaTarowVIEw)_lb.SelectedItem)[Valuename].ToString();
_lb_kd_first_top = _lb.Selectedindex != 0;
}
if (e.KeyCode == Keys.Enter && _lb.Selectedindex != -1)
{
_lb.Visible = false;
this.Height = _tb.Height;
_tb.Focus();
}
}
//列表鼠标单击事件
voID _lb_Click(object sender,EventArgs e)
{
if (_lb.Selectedindex != -1)
{
TextBoxText = ((DaTarowVIEw)_lb.SelectedItem)[Valuename].ToString();
}
_lb.Visible = false;
_tb.Focus();
this.Height = _tb.Height;
}
复制代码 代码如下:
//文本框按键事件
voID _tb_KeyDown(object sender,KeyEventArgs e)
{
if (_lb.Items.Count == 0||!_lb.Visible) return;
bool _is_set = false;
if (e.KeyCode == Keys.Up)
{
if (_lb.Selectedindex <= 0)
{
_lb.Selectedindex = -1;
TextBoxText = _general_text;
}
else
{
_lb.Selectedindex--;
_is_set = true;
}
}
else if (e.KeyCode == Keys.Down)
{
if (_lb.Selectedindex == _lb.Items.Count - 1)
{
_lb.Selectedindex = 0;
_lb.Selectedindex = -1;
TextBoxText = _general_text;
}
else
{
_lb.Selectedindex++;
_is_set = true;
}
}
else if (e.KeyCode == Keys.Enter)
{
_lb.Visible = false;
this.Height = _tb.Height;
_is_set = _lb.Selectedindex != -1;
}
_lb_kd_first_top = _lb.Selectedindex != 0;
if (_is_set)
{
_text_lock = true;
_tb.Text = ((DaTarowVIEw)_lb.SelectedItem)[Valuename].ToString();
_tb.SelectionStart = _tb.Text.Length + 10;
_tb.SelectionLength = 0;
_text_lock = false;
}
}
//文本框文本变更事件
voID _tb_TextChanged(object sender,EventArgs e)
{
if (_text_lock) return;
_general_text = _tb.Text;
_lb.Visible = true;
_lb.Height = _lb.ItemHeight * (_itemCount+1);
this.BringToFront();
_lb.BringToFront();
this.Height = _tb.Height + _lb.Height;
Datatable temp_table = _dt_datasource.Clone();
string filtStr = FormatStr(_tb.Text);
DaTarow [] rows = _dt_datasource.Select(string.Format(GetFilterstr(),Codename,filtStr,_lb.displayMember));
for (int i = 0; i < rows.Length&&i<_itemCount; i++)
{
temp_table.Rows.Add(rows[i].ItemArray);
}
_lb.DataSource = temp_table;
if (_lb.Items.Count > 0) _lb.SelectedItem = _lb.Items[0];
}
复制代码 代码如下:
/// <summary>
/// 初始化控件
/// </summary>
private voID InitialControls()
{
_lb_kd_first_top = true;
_tb = new TextBox();
_tb.Location = new Point(0,0);
_tb.margin = new System.windows.Forms.padding(0);
_tb.WIDth = this.WIDth;
_tb.TextChanged += new EventHandler(_tb_TextChanged);
_tb.KeyUp += new KeyEventHandler(_tb_KeyDown);
_lb = new ListBox();
_lb.Visible = false;
_lb.WIDth = _tb.WIDth;
_lb.margin = new System.windows.Forms.padding(0);
_lb.displayMember = Valuename;
_lb.SelectionMode = SelectionMode.One;
_lb.Location = new Point(0,_tb.Height);
_lb.KeyUp += new KeyEventHandler(_lb_KeyDown);
_lb.Click += new EventHandler(_lb_Click);
this.Controls.Add(_tb);
this.Controls.Add(_lb);
this.Height = _tb.Height - 1;
this.LostFocus += new EventHandler(autoComplete_LostFocus);
this.Leave += new EventHandler(autoComplete_LostFocus);
this.Load += new EventHandler(autoComplete_Load);
}
/// <summary>
/// 获取过滤格式字符串
/// </summary>
/// <returns></returns>
private string GetFilterstr()
{
//未过滤注入的字符 ' ] %任意 *任意
string filter = " {0} like '{1}%' and IsNull([{2}],' ') <> ' ' ";
if (_dt_datasource.Rows[0][Codename].ToString().LastIndexOf(';') > -1)
filter = " {0} like '%;{1}%' and IsNull([{2}],' ') <> ' ' ";
return filter;
}
/// <summary>
/// 过滤字符串中一些可能造成出错的字符
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private string FormatStr(string str)
{
if (string.IsNullOrEmpty(str)) return string.Empty;
str = str.Replace("[","[[]").Replace("%","[%]").Replace("*","[*]").Replace("'","''");
if (Codename == "code") str = str.Replace(" ","");
return str;
}
下面是使用控件的例子
复制代码 代码如下:
class Common
{
/// <summary>
/// 生成测试数据源
/// </summary>
public static Datatable CreateTestDataSoucre
{
get
{
List<keyvaluePair<string,string>> source = new List<keyvaluePair<string,string>>()
{
new keyvaluePair<string,string>("张三",";zs;张三;"),
new keyvaluePair<string,string>("李四",";li;李四;"),string>("王五",";ww;王五;"),string>("赵六",";zl;赵六;"),string>("洗刷",";cs;csharp;c#;洗刷;"),string>("爪哇",";java;爪哇;"),string>("java",";java;"),string>("c#",";c#;cs;csharp;"),string>("JavaScript",";JavaScript;Js;")
};
Datatable table = new Datatable();
table.Columns.Add("ID");
table.Columns.Add("name");
table.Columns.Add("code");
for (int i = 0; i < source.Count; i++)
{
DaTarow row = table.Rows.Add();
row["ID"] = i;
row["name"] = source[i].Key;
row["code"] = source[i].Value;
}
return table;
}
}
}
//.............
autoComplete ac=new autoComplete();
ac.Valuename = "name";
ac.Codename = "code";
ac.DataSource= Common.CreateTestDataSoucre;
ac.ItemCount= 5;
总结
以上是内存溢出为你收集整理的WinForm 自动完成控件实例代码简析全部内容,希望文章能够帮你解决WinForm 自动完成控件实例代码简析所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)