1

ユーザーが範囲外の数値を入力しようとするたびに[0, 24]、エラー メッセージが表示されます。浮動小数点数を受け入れるための私のコードは次のとおりです。範囲検証を追加するように変更するにはどうすればよいですか?

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

2 に答える 2

0

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 = " ";
}
于 2013-05-05T11:02:58.450 に答える