问题描述
我有$ P $使用键按下事件所键入的文本框中pvented数字。但通过鼠标使用Ctrl + V或粘贴内容时,该号码被输入到文本框中。如何prevent呢?我必须让所有的文本粘贴/输入除号。
I have prevented numbers from being typed in text box using key down event. But when using Ctrl+V or pasting content through mouse, the numbers are being entered in the text box. How to prevent this? I have to allow all text to be pasted/typed except numbers.
推荐答案
在比较简单的方法是检查使用框TextChanged
事件文本。如果文字是有效的,保存它的一个副本在一个字符串变量。如果无效,显示一条消息,然后恢复从变量的文字:
On quite simple approach would be to check the text using the TextChanged
event. If the text is valid, store a copy of it in a string variable. If it is not valid, show a message and then restore the text from the variable:
string _latestValidText = string.Empty;
private void TextBox_TextChanged(object sender, EventArgs e)
{
TextBox target = sender as TextBox;
if (ContainsNumber(target.Text))
{
// display alert and reset text
MessageBox.Show("The text may not contain any numbers.");
target.Text = _latestValidText;
}
else
{
_latestValidText = target.Text;
}
}
private static bool ContainsNumber(string input)
{
return Regex.IsMatch(input, @"\d+");
}
这将处理的任何数字出现在文本中,无论在哪里,有多少次,他们可能会出现。
This will handle any occurrence of numbers in the text, regardless of where or how many times they may appear.
这篇关于被粘贴在文本框中的.NET Windows窗体从prevent号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!