I am looking for a way to validate data entered into a textbox which is used to obtain the value entered and take it to mathematical formulas. I already created a function which the user can only enter numbers(0-9), and the characters ".", "," and "-" to write decimals and negatives, but my problem is: when the user enters something like: "..-", ",.,", "-." the program fails. Could you help me? Thanks in advance. I leave you the function to validate how I have it until this minute
public static void SoloNumeros(KeyPressEventArgs V)
{
if (Char.IsDigit(V.KeyChar))
{
V.Handled = false;
}
else if (Char.IsControl(V.KeyChar))
{
V.Handled = false;
}
else if (Char.IsControl(V.KeyChar))
{
V.Handled = false;
}
else if (V.KeyChar.ToString().Equals("."))
{
V.Handled = false;
}
else if (V.KeyChar.ToString().Equals(","))
{
V.Handled = false;
}
else if (V.KeyChar.ToString().Equals("-"))
{
V.Handled = false;
}
else
{
V.Handled = true;
MessageBox.Show("Por favor, introduzca solo nùmeros.");
}
}
You can use the Tryparse method. in your case the bool method (because double accepts it's layers of parsing ".")
It would be something like this :
Tryparse is a function that will try to convert the first string parameter to a number.
if tryparse is successful, the out parameter will be loaded with the value of the conversion and the result of the function will be "true"
but if Tryparse fails, the out parameter will be null and the result of the function will be false
Now I see another problem, and that is that you are trying to validate character by character,
You will not be able to do this in any way to find out if your result is numeric or not, it is preferable that you do a tryparse on it with all the text of the textbox and not character by character.
make the following code that can help you with your question, for your static method of OnlyNumbers make the following code which simplifies your code more
To prevent the number from being wrong when performing the operation and to prevent a number with the following characteristics from passing through the code 3..4, perform the following code.
This code returns a true or a false if the number is correct or incorrect, in your case use a double that will help a lot, if you are looking to do it in real time I recommend you make a regex expression that allows you to validate that the numbers are not repeated characters.
Mike, thank you very much for your answer, I did not know the double.TryParse method, it was a great help, I already found the solution to my problem, create the following method:
//Class Validate
I use this method in the click event of a "Calculate" button that I have in my program. I'm a little more less like this