在工作中遇到一个问题,在查询的时候,用户在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();
}
这样就实现了过滤。
总结,用正则表达式来写过滤类,或许更好,待完善。