C# 文本框中只允许使用字母数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/910063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Allow only alphanumeric in textbox
提问by Sauron
I have a textbox that should disallow entering any special characters.
我有一个不允许输入任何特殊字符的文本框。
The user can enter :
用户可以输入:
- A-Z
- a-z
- 0-9
- Space
- AZ
- 阿兹
- 0-9
- 空间
How can I make the KeyDown
event to do this?
我怎样才能让KeyDown
事件做到这一点?
采纳答案by Szymon Rozga
private void _txtPath_KeyDown(object sender, KeyEventArgs e)
{
if ((e.Key < Key.A) || (e.Key > Key.Z))
e.Handled = true;
}
回答by Gishu
Use a regex to filter out the other characters. Or use Char.IsDigit, IsXXX methods to filter out unwanted characters. Lots of ways to do this.
使用正则表达式过滤掉其他字符。或者使用 Char.IsDigit、IsXXX 方法过滤掉不需要的字符。有很多方法可以做到这一点。
Update: If you must use KeyDown then it seems that you need to also handle KeyPressed and set obEventArgs.Handled = true to disallow the characters. See the example on the KeyDown MSDN Page
更新:如果您必须使用 KeyDown 那么您似乎还需要处理 KeyPressed 并设置 obEventArgs.Handled = true 以禁止这些字符。请参阅KeyDown MSDN 页面上的示例
Update: Now that you specify it's WPF. The below code will allow only a-z and A-Z characters to be entered into the textbox. Extend as needed...
更新:现在您指定它是 WPF。下面的代码将只允许在文本框中输入 az 和 AZ 字符。根据需要扩展...
private void _txtPath_KeyDown(object sender, KeyEventArgs e)
{
if ((e.Key < Key.A) || (e.Key > Key.Z))
e.Handled = true;
}
This will break if you copy-paste stuff into the text-box. Validate the entire text once the user leaves the control or when he clicks OK/Submit as MusicGenesis says.
如果您将内容复制粘贴到文本框中,这将中断。一旦用户离开控件,或者当他像 MusicGenesis 所说的那样单击确定/提交时,验证整个文本。
回答by MusiGenesis
Handling the KeyDown or KeyPress events is one way to do this, but programmers usually forget that a user can still copy-and-paste invalid text into the textbox.
处理 KeyDown 或 KeyPress 事件是实现此目的的一种方法,但程序员通常会忘记用户仍然可以将无效文本复制并粘贴到文本框中。
A somewhat better way is to handle the TextChanged event, and strip out any offending characters there. This is a bit more complicated, as you have to keep track of the caret position and re-set it to the appropriate spot after changing the box's Text property.
更好的方法是处理 TextChanged 事件,并去除那里的任何有问题的字符。这有点复杂,因为您必须跟踪插入符号的位置并在更改框的 Text 属性后将其重新设置到适当的位置。
Depending on your application's needs, I would just let the user type in whatever they want, and then flag the textbox (turn the text red or something) when the user tries to submit.
根据您的应用程序的需要,我只会让用户输入他们想要的任何内容,然后在用户尝试提交时标记文本框(将文本变为红色或其他内容)。
回答by Rune FS
and your regExp could look like [0-9a-zA-Z]* to allow only English alphanumeric chracters
并且您的 regExp 可能看起来像 [0-9a-zA-Z]* 以仅允许英文字母数字字符
回答by GWLlosa
I know that winForms have available a MaskedTextBox control, which lets you specify exactly this sort of thing. I don't know WPF, so I dunno if that's available there, but if it is, do that. Its MUCH easier than all this stuff with keypresses and events, and more robust too.
我知道 winForms 有一个 MaskedTextBox 控件,它可以让你准确地指定这类事情。我不知道 WPF,所以我不知道那里是否可用,但如果是,请执行此操作。它比所有这些带有按键和事件的东西要容易得多,而且也更健壮。
回答by Szymon Rozga
I think it's worth considering doing the filtering on the TextBox's TextChanged event. You can create an operation that gets rid of any non-valid characters from your text string. This is a bit more messy than blocking the KeyDown event.
我认为值得考虑对 TextBox 的 TextChanged 事件进行过滤。您可以创建一个删除文本字符串中任何无效字符的操作。这比阻止 KeyDown 事件要麻烦一些。
But, I think this is the way to go because you are not blocking WPF's built-in KeyDown/Up event handling mechanisms, so copy/paste still works. You would be working at a higher level of abstractions so I think it will be easier to figure out what is going on.
但是,我认为这是要走的路,因为您没有阻止 WPF 的内置 KeyDown/Up 事件处理机制,因此复制/粘贴仍然有效。你会在更高的抽象层次上工作,所以我认为弄清楚发生了什么会更容易。
回答by gr-eg
The easiest way to do this would be to included the Extended WPF Toolkit which has a control for doing exactly what you are asking for by specifying a mask.
执行此操作的最简单方法是包含扩展 WPF 工具包,该工具包具有通过指定掩码来准确执行您要求的操作的控件。
http://wpftoolkit.codeplex.com/wikipage?title=MaskedTextBox&referringTitle=Home
http://wpftoolkit.codeplex.com/wikipage?title=MaskedTextBox&referringTitle=Home
It will also display the mask in the text box as you are inputting if required.
如果需要,它还会在您输入时在文本框中显示掩码。
(It also has many other useful controls)
(它还具有许多其他有用的控件)
回答by miguel
only alphanumeric TextBox WPF C#,
只有字母数字 TextBox WPF C#,
sorry for my english.. but with this code for WPF, c#, I only permit alphanumeric
对不起我的英语..但是对于WPF,c#的这段代码,我只允许字母数字
private void txtTraslado_TextChanged(object sender, KeyEventArgs e)
{
if (((e.Key < Key.NumPad0)||(e.Key > Key.NumPad9))&&((e.Key < Key.A)||(e.Key > Key.Z)))
{
e.Handled = true;
}
}
回答by shane
I ran into this in silverlight and wrote something like this.
我在silverlight中遇到了这个并写了这样的东西。
private string _filterRegexPattern = "[^a-zA-Z0-9]"; // This would be "[^a-z0-9 ]" for this question.
private int _stringMaxLength = 24;
private void _inputTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
if (!string.IsNullOrEmpty(_filterRegexPattern))
{
var text = _inputTextBox.Text;
var newText = Regex.Replace(_inputTextBox.Text, _filterRegexPattern, "");
if (newText.Length > _stringMaxLength)
{
newText = newText.Substring(0, _stringMaxLength);
}
if (text.Length != newText.Length)
{
var selectionStart = _inputTextBox.SelectionStart - (text.Length - newText.Length);
_inputTextBox.Text = newText;
_inputTextBox.SelectionStart = selectionStart;
}
}
}
回答by WhoIsRich
Just wanted to add some code for those ending up here by search:
只是想为那些通过搜索结束的人添加一些代码:
private void Filter_TextChanged(object sender, EventArgs e)
{
var textboxSender = (TextBox)sender;
var cursorPosition = textboxSender.SelectionStart;
textboxSender.Text = Regex.Replace(textboxSender.Text, "[^0-9a-zA-Z ]", "");
textboxSender.SelectionStart = cursorPosition;
}
This is a change filter, so handles copy and paste, and preserves cursor position so that changing text in the middle works properly.
这是一个更改过滤器,因此处理复制和粘贴,并保留光标位置,以便更改中间的文本正常工作。
Note it uses the 'sender' to get the control name, allowing this one function to be linked to multiple textbox boxes, assuming they need the same filter. You can link multiple controls by going to the event section of a control and manually picking the function for the TextChanged event.
请注意,它使用“发送者”来获取控件名称,假设它们需要相同的过滤器,则允许将这个函数链接到多个文本框。您可以通过转到控件的事件部分并手动选择 TextChanged 事件的函数来链接多个控件。