Reputation: 23
Whenever the user tries to enter a number not in the range [0, 24]
it should show an error message. My code to accept floating point numbers is as follows. How can I modify it to add range validation?
private void h(object sender, Windows.UI.Xaml.Controls.TextChangedEventArgs e)
{
try
{
float time = float.Parse(hours.Text);
}
catch
{
label2.Text = "enter proper value ";
hours.Text = " ";
}
}
Upvotes: 1
Views: 5321
Reputation: 45096
I know SO discourages just posting a link as an answer but in the case the link is a direct and full answer to the question.
Upvotes: 2
Reputation: 28520
I would recommend using float.TryParse
, rather than building a try-catch block in case the parse fails. TryParse
will return the value of the parse in the out
variable, and true if the parse is successful and false if it isn't. Combine that with a check to see if the number is between 0 and 24, and you have something that looks like this:
float parsedValue;
// If the parse fails, or the parsed value is less than 0 or greater than 24,
// show an error message
if (!float.TryParse(hours.Text, out parsedValue) || parsedValue < 0 || parsedValue > 24)
{
label2.Text = "Enter a value from 0 to 24";
hours.Text = " ";
}
Upvotes: 0