110,536
社区成员
发帖
与我相关
我的任务
分享
namespace WindowsFormsApplication1
{
public partial class Form4 : Form
{
public Form4()
{
InitializeComponent();
// 构造数据
loaddata();
}
// 构造数据源
private DataTable mdataSource = new DataTable();
// 特殊出标志
private bool flag = false;
private DataTable dtfliter = new DataTable();
// 初始化数据
/// <summary>
/// 构造数据
/// </summary>
private void loaddata()
{
DataTable dt = new DataTable();
dt.Columns.Add("name", typeof(string));
dt.Columns.Add("value", typeof(string));
DataRow dr0 = dt.NewRow();
dr0["name"] = string.Empty;
dr0["value"] = "0";
dt.Rows.Add(dr0);
DataRow dr1 = dt.NewRow();
dr1["name"] = "1X#-100";
dr1["value"] = "1X#-100";
dt.Rows.Add(dr1);
DataRow dr2 = dt.NewRow();
dr2["name"] = "1X#-1200";
dr2["value"] = "1X#-1200";
dt.Rows.Add(dr2);
DataRow dr3 = dt.NewRow();
dr3["name"] = "abc";
dr3["value"] = "3";
dt.Rows.Add(dr3);
DataRow dr4 = dt.NewRow();
dr4["name"] = "time";
dr4["value"] = "4";
dt.Rows.Add(dr4);
DataRow dr5 = dt.NewRow();
dr5["name"] = "this is a max length string to test if the dropdownwith is autochange";
dr5["value"] = "5";
dt.Rows.Add(dr5);
DataRow dr6 = dt.NewRow();
dr6["name"] = "date";
dr6["value"] = "6";
dt.Rows.Add(dr6);
DataRow dr7 = dt.NewRow();
dr7["name"] = "time and date";
dr7["value"] = "7";
dt.Rows.Add(dr7);
dt.AcceptChanges();
mdataSource = dt;
BindDate(mdataSource);
}
private void BindDate(DataTable dt)
{
this.comboBox1.DataSource = dt;
this.comboBox1.DisplayMember = "name";
this.comboBox1.ValueMember = "value";
comboBox1.SuspendLayout();
}
/// <summary>
/// combobox 输入事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void comboBox1_KeyUp(object sender, KeyEventArgs e)
{try{
if (this.comboBox1.Text == string.Empty)
{
BindDate(mdataSource);
this.comboBox1.Text = string.Empty;
return;
}
flag = false;
string str = this.comboBox1.Text;
// 根据输入的值自带筛选
bool validate = Fillter(str);
// 现实下拉框
this.comboBox1.DroppedDown = true;
// 输入无效的数据
this.comboBox1.Text = str;
if (comboBox1.Text != null && comboBox1.Text != string.Empty)
{
// 获得光标位置
this.comboBox1.SelectionStart = comboBox1.Text.Length;
}
// 现实鼠标
this.comboBox1.Cursor = Cursors.Default;
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// 筛选匹配的值
/// </summary>
/// <param name="str"></param>
private bool Fillter(string str)
{
bool isvalida = true;
DataTable dt = mdataSource.Clone();
// 循环筛选匹配的值
foreach (DataRow dr in mdataSource.Rows)
{
int i = -1;
i = dr["name"].ToString().IndexOf(str.ToString());
if (i > -1)
{
DataRow newrow = dt.NewRow();
newrow.ItemArray = dr.ItemArray;
// 构造新的数据
dt.Rows.Add(newrow);
}
}
dt.AcceptChanges();
BindDate(dt);
// 当为一条数据要特殊处理/不然光标返回有问题
if (dt.Rows.Count == 1)
{
// 特殊处理标志
flag = true;
this.comboBox1.Text = str;// str 参数为输入的值;
int len = str.Length;
}
return isvalida;
}
}
}