winform Textbox模糊搜索实现下拉显示+提示文字
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace _04TextBox { public partial class Form1 : Form { List<string> Data = new List<string>(); string Randomstr = "功夫撒黑胡椒hcbvf蜂窝qwertyuiopasdfghjklzxcvbnm法国的恢复到飞范德萨QWERTYUIOPASDFGHJKLZXCVBNM出现过热423贴①46546也有一头热刚恢复到贴3天赋如头3广泛的我让他"; Random rd = new Random(GetRandomSeed()); static int GetRandomSeed() { byte[] bytes = new byte[4]; System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider(); rng.GetBytes(bytes); return BitConverter.ToInt32(bytes, 0); } public Form1() { InitializeComponent(); //2000W数据,这里会有卡顿现象,这里修改为200W for (int i = 0; i < 2000000; i++) { Data.Add(Randomstr.ToCharArray()[rd.Next(Randomstr.Length)].ToString() + Randomstr.ToCharArray()[rd.Next(Randomstr.Length)].ToString() + Randomstr.ToCharArray()[rd.Next(Randomstr.Length)].ToString() + Randomstr.ToCharArray()[rd.Next(Randomstr.Length)].ToString() + Randomstr.ToCharArray()[rd.Next(Randomstr.Length)].ToString()); } //重点代码 this.textBox1.AutoCompleteCustomSource.Clear(); this.textBox1.AutoCompleteCustomSource.AddRange(Data.ToArray()); this.textBox1.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend; this.textBox1.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.CustomSource; } private void Form1_Load(object sender, EventArgs e) { } } }
提示内容,加个变量跟两个事件
#region 实现提示文字 Boolean textboxHasText = false;//判断输入框是否有文本 /// <summary> /// textbox获得焦点 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void textBox1_Enter(object sender, EventArgs e) { if (textboxHasText == false) textBox1.Text = ""; textBox1.ForeColor = Color.Black; } /// <summary> /// textbox失去焦点 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void textBox1_Leave(object sender, EventArgs e) { if (textBox1.Text == "") { textBox1.Text = "提示内容"; textBox1.ForeColor = Color.LightGray; textboxHasText = false; } else textboxHasText = true; } #endregion
作者:三小
声明:原创博客请在转载时保留原文链接或者在文章开头加上本人博客地址,如发现错误,欢迎批评指正。凡是转载于本人的文章,不能设置打赏功能,如有特殊需求请与本人联系!