I'm trying to put some controls on my TextBox
using Visual Studio 2019 WinForms.
So this is my big control
int myNumber;
private void txtNumberControl_TextChanged(object sender, EventArgs e)
{
try
{
if (sender != null)
{
myNumber = Convert.ToInt32(txtNumberControl.Text);
}
}
catch (Exception)
{
MessageBox.Show("You can write only numbers!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
As you can see from the code above, I'm trying to make sure that the user inputs only numeric values. The strange behavior starts after 10 numbers writed. So if I write 12345678912 it goes in catch
and shows me the MessageBox
error message.
Here is a picture of it (it's in Italian but the error is the same I just translated it).
myErrorMessage
But the most strange part is that I can put down how many 00000000000000000000000000
I want and It just works as expected.
I'm seeking for help, can someone gently explain me why is this happening?
Your program goes into the catch because the number you wanted to enter is now to high to be converted into an integer.
Max Value for an integer is: 2147483647
You've gone over that limit with: 12345678912
Because of that your program fails to convert and prints the message even tough your input is a legit number.
To actually check if the whole inputed string is a number even if it is over the integer limit. You can use .IsDigit()
combined with .All()
to check if any of the letters is not a number.
Example:
public bool CheckForNumber(string yourString) {
// Check if all chars in this string are digits.
if (yourString.All(char.IsDigit)) {
return true;
}
return false;
}
We can now use that function in combination with the User input to check if it is a valid number.
private void txtNumberControl_TextChanged(object sender, EventArgs e) {
// Check the text of the object that triggered this Event.
if (!CheckForNumber((sender as Control).Text)) {
MessageBox.Show("You can write only numbers!", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// Try to parse the text into a long (is 0 if the input is invalid).
if (!long.TryParse(txtNumberControl.Text, out long number)) {
// Not validated
}
}