c# 自动填充的ComboBox,可以展开ComboBox并高亮选中的内容。

public partial class ACComboBox : System.Windows.Forms.ComboBox

{    

   private bool autoComplete;

        [DefaultValue(true),
        Description("Auto-completes text if a match is found in the items collection."), Category("Behavior")]
        public bool AutoComplete
        {
            get { return autoComplete; }
            set { autoComplete = value; }
        }


        public ACComboBox()
        {
            // This call is required by the Windows.Forms Form Designer.
            InitializeComponent();
            // Add any initialization after the InitComponent call
            this.autoComplete = true;
            this.KeyPress += new KeyPressEventHandler(this.OnKeyPress);
        }


        public ACComboBox(IContainer container)
        {
            container.Add(this);

            InitializeComponent();
            this.autoComplete = true;
            this.KeyPress += new KeyPressEventHandler(this.OnKeyPress);
        }

        private void OnKeyPress(object sender, KeyPressEventArgs e)
        {
            if (autoComplete)
            {
                ACComboBox acComboBox = (ACComboBox)sender;
                if (!e.KeyChar.Equals((char)8))
                {
                    SearchItems(acComboBox, ref e);
                }
                else
                    e.Handled = false;
            }
            else
                e.Handled = false;
        }

        /// <summary>
        /// Searches the combo box item list for a match and selects it.
        /// If no match is found, then selected index defaults to -1.
        /// </summary>
        ///<param name="&quot;acComboBox&quot;" />
        ///<param name="&quot;e&quot;" />
        private void SearchItems(ACComboBox acComboBox, ref KeyPressEventArgs e)
        {
            int selectionStart = acComboBox.SelectionStart;
            int selectionLength = acComboBox.SelectionLength;
            int selectionEnd = selectionStart + selectionLength;
            int index;
            StringBuilder sb = new StringBuilder();

            sb.Append(acComboBox.Text.Substring(0, selectionStart))
                .Append(e.KeyChar.ToString())
                .Append(acComboBox.Text.Substring(selectionEnd));
            index = acComboBox.FindString(sb.ToString());

            if (index == -1)
                e.Handled = false;
            else
            {
                acComboBox.SelectedIndex = index;
                acComboBox.Select(selectionStart + 1, acComboBox.Text.Length - (selectionStart + 1));
                e.Handled = true;
            }
        }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值