验证 Windows 窗体应用程序中的文本框
如何使用 C#.net 在 Windows 窗体应用程序中验证文本框而不允许空格 在我的项目中。我可以验证文本框,不允许空格...... 在这两件事中...................... 1.仅不允许有空格 2.输入一两个字符后文本框接受空格.........
how to validate the textbox without allowing spaces in windows form application using C#.net
in my project .i can validate the text box ,without allowing spaces....
in this two things .............
1.only spaces are not allowed
2.after entering one or two characters textbox accept spaces...........
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
来限制用户在
TextBox
中输入空格。您可以通过处理
KeyPress
事件EDIT如果输入一两个字符后允许输入空格,那么你应该使用
textbox1.Text.TrimStart()
You can restrict the user from entering space in the
TextBox
by handling theKeyPress
eventEDIT
In case space is allowed after entering a character or two , then you should be using
textbox1.Text.TrimStart()
这取决于您所说的“验证”是什么意思。 Winforms 具有当您离开控件时触发的
Validating
和Validate
事件。然后您可以利用这些并验证您的文本框。但是,如果您想在键入时进行验证,则需要使用Key_Press
事件在每次按下按键时进行检查,以确保框中的信息仍然有效。这是一篇关于验证的文章:
WinForm UI Validation
那里的答案给出了一些不同的想法,具体取决于什么你想做的事。无论您做出什么决定,请务必确保正确检查该字段。例如,如果您使用
Key_Press
,请不要在允许空格之前只计算字段中有多少个字符。如果您这样做,用户可能会将光标移动到开头并按空格键。那会弄乱你的系统。即使您使用的是Key_Press
事件,请确保在验证时检查整个字段。根据您想要的复杂模式使用正则表达式。It depends on what you mean by "validate". Winforms has the
Validating
andValidate
events that fire when you leave a control. You could tap into these and validate your textbox then. However, if you want to validate as you type, you want to use theKey_Press
event to check every time a key is pressed to be sure the information in the box is still valid.Here is a SO article on validation:
WinForm UI Validation
The answers in there give some different ideas depending on what you want to do. Whatever you decide, be sure to make sure you check the field properly. For example, if you use
Key_Press
, don't just count how many characters are in the field before allowing a space. If you did that, the user could have moved the cursor to the beginning and pressed space. That would mess up your system. Make sure to check the entire field when you validate, even if you are using theKey_Press
event. Use RegEx with as complex a pattern as you want to do this.如果您不想允许在 TextBox 中输入除字母数字字符之外的任何其他字符,则可以在 TextBox 的 KeyPress 事件上执行此操作。
在KeyPress事件中,您需要检查输入的字符是字母还是数字。
Char.IsLetterOrDigit(e.KeyChar)
允许按键
如果是,则设置“e.Handled = false”
,否则设置“e.Handled = true”不允许按键
If you don't want to allow any other characters entry except for the alphanumeric characters in a TextBox, then you can do this on the KeyPress event of a TextBox.
In the KeyPress Event, you need to check whether the entered character is either a Letter or a Digit.
Char.IsLetterOrDigit(e.KeyChar)
If yes, then allow the Key pressing by setting
"e.Handled = false"
Otherwise, don't allow the Key pressing by setting "e.Handled = true"