+ 1
Help me with c#
I am making a c# Calculator. I want that if someone enters a letter instead of a number, they will get a warning about how to enter text. I have in mind the idea to write a huge code, like if ((num1 != 1)||(num1 != 2)) and so on, to check whether there is a number in the text, and if there are none, then output an error. But is it possible to make it shorter? Do not check each digit for presence in the text, but do something in General?
1 Resposta
0
You can use regex in textbox textchanged like this:
if(System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "[^0-9]")) { MessageBox.Show("Please enter only numbers.");
textBox1.Text =textBox1.Text.Remove(textBox1.Text.Length - 1); }
You can handle it via keypress as:
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar)) { e.Handled = true; }