Processing strategy:
Traversing and judging the Textbox string in the TextChanged method of TextBox. The code is as follows
:
///
/// Determine whether a character is a letter or a number
///
/// Boolean IsNumOrLetter(String str) { char[] tmpCharArray = str.ToCharArray(); if( ((tmpCharArray[0 ] >= 'A') && (tmpCharArray[0] <= 'Z')) || ((tmpCharArray[0] >= 'a') && (tmpCharArray[0] <= 'z')) || ( (tmpCharArray[0] >= '0') && (tmpCharArray[0] < '9')) ) { return true; } else { return false; } }
private void textBox1_TextChanged(object sender, EventArgs e)
{
for (int i = 0; i < textBox1.Text.Length; i++)//遍历判断TextBox中的字符
{
string tmpStr = textBox1.Text.Substring(i, 1);
if (IsNumOrLetter(tmpStr) == false)
{
textBox1.Text = textBox1.Text.Remove(i, 1);
textBox1.SelectionStart = textBox1.Text.Length;
}
}
}
}