如何让textbox输入的全角数字自动转换为半角数字
我一个textbox输入身份证,如果用户输入的是全角数字就自动转换成半角数字。最好是在textchanged事件中判断。
[解决办法]
- C# code
public string NarrowToSmall(string inputString){ char[] c = inputString.ToCharArray(); for (int i = 0; i < c.Length; i++) { byte[] b = System.Text.Encoding.Unicode.GetBytes(c,i,1); if (b.Length == 2) { if (b[1] == 255) { b[0] = (byte)(b[0] + 32); b[1] = 0; c[i] = System.Text.Encoding.Unicode.GetChars(b)[0]; } } } string returnString = new string(c); return returnString; // 返回半角字符 }
[解决办法]
- C# code
private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { if ((int)e.KeyChar >= 65296 && (int)e.KeyChar <= 65305) { e.KeyChar = (char)((int)e.KeyChar - 65248); } }