简体   繁体   English

C#文本框-仅接受范围内的浮点数

[英]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. 每当用户尝试输入不在[0, 24]范围内的数字时[0, 24]它都会显示一条错误消息。 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. 我建议使用float.TryParse ,而不是在解析失败的情况下构建try-catch块。 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. TryParse将在out变量中返回解析的值,如果解析成功,则返回true,否则返回false。 Combine that with a check to see if the number is between 0 and 24, and you have something that looks like this: 将其与检查结合起来以查看数字是否在0到24之间,并且您将看到以下内容:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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