您的位置:首页 > 其它

TextBox自动完成控件

2014-11-12 16:50 162 查看
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Data;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;

namespace LHXETDDataManagement.Controls
{
/// <summary>
/// TextBox扩展类
/// </summary>
public class AutoCompleteTextBox : System.Windows.Forms.TextBox
{
private bool _isSelect = false;
private ListBox _lboxSearch = null;

public AutoCompleteTextBox()
{
this.DataSouce = new List<string>();
this.PanelMaxHeight = 130; //10行
}

/// <summary>
/// 获取或设置自动完成数据源
/// </summary>
public List<string> DataSouce { set; get; }

/// <summary>
/// 获取或设置面版最大高度
/// </summary>
public int PanelMaxHeight { set; get; }

protected override void OnKeyPress(KeyPressEventArgs e)
{
_isSelect = false;

base.OnKeyPress(e);
}

protected override void OnKeyDown(KeyEventArgs e)
{
if (_lboxSearch == null) { return; }
int index = _lboxSearch.SelectedIndex;
switch (e.KeyCode)
{
case Keys.Up:
index--;
break;
case Keys.Down:
index++;
break;
case Keys.Enter:
LboxSearch_Click(_lboxSearch, new EventArgs());
break;
}
if (index < 0) { index = 0; }
if (index >= _lboxSearch.Items.Count) { index = _lboxSearch.Items.Count - 1; }
_lboxSearch.SelectedIndex = index;

base.OnKeyDown(e);
}

protected override void OnTextChanged(EventArgs e)
{
base.OnTextChanged(e);

Control parent = this.Parent;
string text = this.Text.Trim();
if (_lboxSearch != null)
{
parent.Controls.Remove(_lboxSearch);
}

if (string.IsNullOrEmpty(text) ||
DataSouce == null ||
DataSouce.Count == 0)
{
return;
}

List<string> list = DataSouce.Where(p => p.Contains(text)).ToList();
if (list.Count > 0 && !_isSelect)
{
int height = list.Count * 13;
if (height >= PanelMaxHeight)
{
height = PanelMaxHeight;
}

_lboxSearch = new ListBox();
_lboxSearch.Location = new Point(this.Location.X, this.Location.Y + this.Size.Height);
_lboxSearch.Size = new Size(this.Size.Width, height);
_lboxSearch.Items.AddRange(list.ToArray());
_lboxSearch.Click += new EventHandler(LboxSearch_Click);
parent.Controls.Add(_lboxSearch);
//置顶
_lboxSearch.BringToFront();
}
}

private void LboxSearch_Click(object sender, EventArgs e)
{
if (_lboxSearch != null)
{
_isSelect = true;

this.Text = _lboxSearch.Text;
this.Focus();
this.SelectionStart = this.Text.Length;
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息