心有多高,就飞多高

天高任鸟飞

博客园 首页 联系 订阅 管理

       这个写的比较简单还没做封装 指定combobox的数据源为必须datatable .有兴趣的可以做参考,重新封装.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        // 构造函数
        public Form1()
        {
            InitializeComponent();
            // 构造数据
            loaddata();
        }
        // 构造数据源
        private DataTable mdataSource = 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"] = "a";
            dr1["value"] = "1";
            dt.Rows.Add(dr1);
            DataRow dr2 = dt.NewRow();
            dr2["name"] = "ab";
            dr2["value"] = "2";
            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";
            // 自带调整下拉框
            AutoSizeComboBoxItem(this.comboBox1);
            comboBox1.SuspendLayout();
        }
        private DataTable dtfliter = new DataTable();
        // 特殊出标志
        private bool flag = false;       
        /// <summary>
        /// combobox 输入事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBox1_KeyUp(object sender, KeyEventArgs e)
        {
            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;
             // 输入无效的数据
             if (!validate)
             {
                 MessageBox.Show("输入的数据无效,请重新输入");               
             }
             else
             {
                 this.comboBox1.Text = str;
                 if (comboBox1.Text != null && comboBox1.Text != string.Empty)
                 {
                     // 获得光标位置
                     this.comboBox1.SelectionStart = comboBox1.Text.Length;
                 }
             }
           
            // 现实鼠标
            this.comboBox1.Cursor   = Cursors.Default;     
       
        }
        /// <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 (flag  && dt.Rows.Count > 1)
            //{
            //    this.comboBox1.Text = str;
            //    return;
            //}
            // 当为一条数据要特殊处理/不然光标返回有问题
            if (dt.Rows.Count == 1)
            {
                // 特殊处理标志
                flag = true;
                this.comboBox1.Text = str;// str参数为输入的值;
                int len = str.Length;
               // Fillter(str.Substring(0, len - 1));
            }
            // 当数据源中没有输入的值提示, 并且截断字符重新筛选
            if (dt.Rows.Count == 0)
            {
                if (str.Length > 0)
                {
                    int i = str.Length - 1;
                    Fillter(str.Substring(0, i));                    
                    isvalida = false;
                }
               
            }
            return isvalida;
        }       
    
        /// <summary>
        /// 自动调整宽度
        /// </summary>
        /// <param name="sender"></param>
        public void AutoSizeComboBoxItem(object sender)
        {
            Graphics g = null; Font font = null;
            try
            {
                ComboBox senderComboBox = sender as ComboBox;

                int width = senderComboBox.Width;
                g = senderComboBox.CreateGraphics();
                font = senderComboBox.Font;

                //checks if a scrollbar will be displayed.
                //If yes, then get its width to adjust the size of the drop down list.
                int vertScrollBarWidth =
                     (senderComboBox.Items.Count > senderComboBox.MaxDropDownItems)
                     ? SystemInformation.VerticalScrollBarWidth : 0;

                int newWidth;
                // 取得数据源
                DataTable dt = (DataTable)senderComboBox.DataSource;
                foreach (DataRow s in dt.Rows)  //Loop through list items and check size of each items.
                {
                    if (s != null)
                    {
                        newWidth = (int)g.MeasureString(s["name"].ToString().Trim(), font).Width
                            + vertScrollBarWidth;
                        if (width < newWidth)
                            width = newWidth;   //set the width of the drop down list to the width of the largest item.
                    }
                }
                this.comboBox1.DropDownWidth = width;
            }
            catch
            { }
            finally
            {
                if (g != null)
                    g.Dispose();
            }

        }
        /// <summary>
        ///  下拉事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            AutoSizeComboBoxItem(this.comboBox1);           
        }       
       
    }
}

 

posted on 2009-04-25 10:51  lankoboy  阅读(2606)  评论(0)    收藏  举报