C# Input Validation Check for positive numbers
-
07-02-2021 - |
Вопрос
I am learning C# and stuck on a problem where I have to check if the user input a VALID currency amount. i.e. no alphabetical character and no negative numbers.
So far I have everything in the program complete EXCEPT that particular input validation.
to convert the input to numeric values i have: originalRate = Double.Parse(txtValue.Text);
then below that i am stumped, i have been messing around with: bool isValid = Double.TryParse(txtValue.Text, );
The common compiler runtime error I get while messing around is Input string was not in a correct format. Which i know it is, that is what I am checking for.
I know this is super basic stuff (this is my first C# class). I have searched around on stack overflow and none of the similar solutions make much sense to me at this point. I have been told to use the TryParse method of the decimal class, however feel as though I am using it wrong and incomplete.
Thank you in advance for your help.
Решение
Here's how you use double.TryParse()
double d;
bool isValid = Double.TryParse(txtValue.Text, out d);
the MDSN page has some examples.
To parse currency string, you could use the second overload of double.TryParse()
and try something like
double d;
bool isValid = double.TryParse(txtValue.Text, NumberStyles.Currency, CultureInfo.GetCultureInfo("en-US"), out d);
Другие советы
double result;
if (double.TryParse(txtValue.text, out result))
{
// The user typed a valid number.
// Do something with it (it’s in “result”).
}
else
{
// The user typed something invalid.
MessageBox.Show("Please type in a number.");
}