简体   繁体   中英

c# text box - Accept only floating point numbers inside a range

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 = " ";
   } 
}

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.

Validation Class

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 = " ";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM