C#Numeric Only TextBox控件

我使用的是C#.NET 3.5,我的项目有问题。 在C#Windows应用程序中,我想使textbox只接受数字。 如果用户尝试输入字符,则消息应显示为“请仅输入数字”,而在另一个文本框中,它必须接受有效的email id消息,如果无效则应显示。 它必须显示无效的用户ID。

我建议你使用MaskedTextBox: http : //msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.aspx

从C#3.5我假设你正在使用WPF。

只需将一个从整数属性到文本框的双向数据绑定。 WPF将自动显示validation错误。

对于电子邮件案例,从在setter中执行Regexpvalidation的字符串属性进行双向数据绑定,并在validation错误时抛出exception。

在MSDN上查找绑定。

使用此代码:

 private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { const char Delete = (char)8; e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete; } 

您可能希望在KeyPress(object, KeyPressEventArgs)事件中尝试int.TryParse(string, out int)来检查数值。 对于其他问题,您可以使用正则表达式。

我使用了@fjdumont提到的TryParse,但是在validation事件中。

 private void Number_Validating(object sender, CancelEventArgs e) { int val; TextBox tb = sender as TextBox; if (!int.TryParse(tb.Text, out val)) { MessageBox.Show(tb.Tag + " must be numeric."); tb.Undo(); e.Cancel = true; } } 

我将它附加到两个不同的文本框中,在我的表单中初始化代码。

  public Form1() { InitializeComponent(); textBox1.Validating+=new CancelEventHandler(Number_Validating); textBox2.Validating+=new CancelEventHandler(Number_Validating); } 

我还添加了tb.Undo()来支持无效更改。

这种方式对我来说是正确的:

 private void textboxNumberic_KeyPress(object sender, KeyPressEventArgs e) { const char Delete = (char)8; e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete; } 

尝试这个代码

 // Boolean flag used to determine when a character other than a number is entered. private bool nonNumberEntered = false; // Handle the KeyDown event to determine the type of character entered into the control. private void textBox1_KeyDown(object sender, KeyEventArgs e) { // Initialize the flag to false. nonNumberEntered = false; // Determine whether the keystroke is a number from the top of the keyboard. if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9) { // Determine whether the keystroke is a number from the keypad. if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9) { // Determine whether the keystroke is a backspace. if (e.KeyCode != Keys.Back) { // A non-numerical keystroke was pressed. // Set the flag to true and evaluate in KeyPress event. nonNumberEntered = true; } } } } private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { if (nonNumberEntered == true) { MessageBox.Show("Please enter number only..."); e.Handled = true; } } 

来源是http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress(v=VS.90).aspx

您可以在TextBox的KeyPress事件上通过e.keychar检查Ascii值。

通过检查AscII值,您可以检查数字或字符。

同样,您可以编写逻辑来检查电子邮件ID。

我认为它会对你有所帮助

  

 try { int temp=Convert.ToInt32(TextBox1.Text); } catch(Exception h) { MessageBox.Show("Please provide number only"); }