C# Win Forms 文本框掩码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2259850/
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
Win Forms text box masks
提问by eomeroff
How can I put mask on win form text box so that it allows only numbers? And how it works for another masks data, phone zip etc.
如何在 win 表单文本框上放置掩码,使其只允许数字?以及它如何用于另一个面具数据、电话拉链等。
I am using Visual Studio 2008 C#
我正在使用 Visual Studio 2008 C#
Thanks.
谢谢。
采纳答案by Mark Byers
Do you want to prevent input that isn't allowed or validate the input before it is possible to proceed?
您想阻止不允许的输入还是在可以继续之前验证输入?
The former could confuse users when they press keys but nothing happens. It is usually better to show their keypresses but display a warning that the input is currently invalid. It's probably also quite complicated to set up for masking an email-address regular expression for example.
前者可能会使用户在按键时感到困惑,但没有任何反应。通常最好显示他们的按键,但显示输入当前无效的警告。例如,设置屏蔽电子邮件地址正则表达式可能也非常复杂。
Look at ErrorProviderto allow the user to type what they want but show warnings as they type.
查看ErrorProvider以允许用户键入他们想要的内容,但在键入时显示警告。
For your first suggestion of a text box that only allows numbers, you might also want to consider a NumericUpDown.
对于只允许数字的文本框的第一个建议,您可能还需要考虑一个NumericUpDown。
回答by Brett Allen
You can use the MaskedTextBox control
您可以使用 MaskedTextBox 控件
http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.aspx
http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.aspx
回答by mitchA
You might want to check out How to: Create a Numeric Text Box.
您可能想查看如何:创建数字文本框。
回答by pfeds
As said above, use a MaskedTextBox.
如上所述,使用MaskedTextBox。
It's also worth using an ErrorProvider.
也值得使用ErrorProvider。
回答by RekhaShanmugam
Use Mask Text box and assign MasktextboxId.Mask.
使用 Mask Text 框并指定 MasktextboxId.Mask。
If u want to use textbox then you have to write Regular Expression for it
如果你想使用文本框,那么你必须为它编写正则表达式
回答by Ashraf Abusada
Control the user's key press event to mask the input by not allowing any unwanted characters.
控制用户的按键事件以通过不允许任何不需要的字符来屏蔽输入。
To allow only numbers with decimals:
只允许带小数的数字:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
// allows 0-9, backspace, and decimal
if (((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 46))
{
e.Handled = true;
return;
}
// checks to make sure only 1 decimal is allowed
if (e.KeyChar == 46)
{
if ((sender as TextBox).Text.IndexOf(e.KeyChar) != -1)
e.Handled = true;
}
}
To allow only phone numbers values:
仅允许电话号码值:
private void txtPhone_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar >= '0' && e.KeyChar <= '9') return;
if (e.KeyChar == '+' || e.KeyChar == '-') return;
if (e.KeyChar == 8) return;
e.Handled = true;
}