过滤TextBox输入框

    在工作中遇到一个问题,在查询的时候,用户在textbox中随机输入,如果输入了特殊字符,必然“’”,就会引起错误,其实原因很简单,这里的单引号在进行数据库操作的时候,和数据库语句或者存储过程中的发生了冲突,所以要进行输入的过滤,这里只允许输入数字和字母。过滤如下:

先写一个实现过滤的类,在初始化的时候传入控件的引用。如下:

namespace Common
{
    public class FilterTextBox
    {
        private TextBox textbox;
        public FilterTextBox(TextBox txtBox)
        {
            this.textbox = txtBox;
        }

        public void Filter()
        {
            char[] characters = this.textbox.Text.ToCharArray();


            if (characters == null || characters.Length == 0)
                return;

 

            for (int i = 0; i < characters.Length; i++)
            {
                char charInput = characters[i];

                //这里使用现成的方法

                if (!Char.IsLetterOrDigit(charInput))
                {
                    if (this.textbox.Text != "")
                    {
                        this.textbox.Text = this.textbox.Text.Remove(i, 1);
                        characters = this.textbox.Text.ToCharArray();

                        //将光标定位在字符后面
                        this.textbox.SelectionStart = i;

                        i--;
                    }
                }
            }
        }
    }
}
这个类是通用的,在需要过滤的模块中产生实例:

        private FilterTextBox filterTextBox;
        public InitVideoListCtrl()
        {
            InitializeComponent();

            this._tran = new TransferHandle();

            //这里传入的是textbox控件
            filterTextBox = new FilterTextBox(this.txtSearchKey);
        }

 

在此需要过滤的textbox的事件中过滤(filter)即可,如下:

        private void txtSearchKey_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            if (e.KeyValue == 37 || e.KeyValue == 38 || e.KeyValue == 39 || e.KeyValue == 40)
                return;

            filterTextBox.Filter();
        }

这样就实现了过滤。

总结,用正则表达式来写过滤类,或许更好,待完善。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值