C#ComboBox自动搜索框功能的实现(二)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
 
namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        private List<string> listNames = new List<string>();
        public Form1()
        {
            InitializeComponent();
            this.comboBox1.Items.Add("ganquanfu");
            this.comboBox1.Items.Add("quanfu");
            this.comboBox1.Items.Add("ligang");
            this.comboBox1.Items.Add("zhaojialong");
            this.comboBox1.Items.Add("zhaozhen");
            this.comboBox1.Items.Add("ganquanfu");
            this.comboBox1.Items.Add("quanfu");
            this.comboBox1.Items.Add("ligang");
            this.comboBox1.Items.Add("zhaojialong");
            this.comboBox1.Items.Add("zhaozhen");
            this.comboBox1.Items.Add("ganquanfu");
            this.comboBox1.Items.Add("quanfu");
            this.comboBox1.Items.Add("ligang");
            this.comboBox1.Items.Add("zhaojialong");
            this.comboBox1.Items.Add("zhaozhen");
 
 
            foreach (var item in comboBox1.Items)
            {
                listNames.Add(item.ToString());
            }
 
            //设置DropDown的高度
           // this.comboBox1.DropDownHeight = 100;
            //以下是事件处理函数的另一种写法,Lambda表达式书写
 
            this.comboBox1.TextUpdate += (a, b) =>
            {
                string search = comboBox1.Text.Trim();
                if (string.IsNullOrWhiteSpace(search))
                {
                    return;
                }
                comboBox1.Items.Clear();
                var results = listNames.Where(t => t.Contains(search)).ToArray();
                //foreach (var item in results)
                //{
                //    comboBox1.Items.Add(item);
 
                //}
          
                if (results.Count()>0)
                {
                    comboBox1.Items.AddRange(results);
                    
                }
                
                comboBox1.DroppedDown = true;
                comboBox1.SelectionStart = search.Length;
            };
        }
                
                         
         private void Form1_Load(object sender, EventArgs e)
        {
            this.Cursor = System.Windows.Forms.Cursors.Cross;
 
        }
    }
}
posted @ 2013-05-04 00:22  Predator  阅读(785)  评论(0编辑  收藏  举报