C#Windows窗体FormatException未处理

时间:2018-02-11 14:34:51

标签: c#

我试图在一个文本框中检查值不超过100但是我得到formatExeception可以在这方面帮助任何人..在此先感谢。

private void textBox1_TextChanged(object sender, EventArgs e)
{
    if (Int32.Parse(textBox1.Text) > 100)
    {
        MessageBox.Show("No. Of Elements Must be Less Then 100");
    }
}

4 个答案:

答案 0 :(得分:0)

如果文本框的内容无法解析为Int32,则需要使用try-catch包围语句。假设您遇到异常,则可以获得描述错误原因的消息。

答案 1 :(得分:0)

如果您只希望用户输入数字但发生错误,则可能更好地使用数字更新,因为文本框中的文本无法解析为数字。使用int.TryParse。如果无法将字符串解析为数字

,它不会抛出异常
        int numElements = 0;
        int.TryParse(textBox1.Text, out numElements);
        if(numElements >100){
            MessageBox.Show("No. Of Elements Must be Less Then 100");
        }

答案 2 :(得分:0)

private void textBox1_TextChanged(object sender, EventArgs e)
{
    int parsed = 0;
    if (!int.TryParse(textBox1.Text), out parsed)
    {
        MessageBox.Show("No. You must enter a number!");
        return;
    }
    if (parsed > 100)
    {
        MessageBox.Show("No. Of Elements Must be Less Then 100");
    }
}

答案 3 :(得分:0)

Parse在解析错误时抛出异常的属性是quite Vexing。它是如此的虚荣,Framework Developers在2.0版本中添加了TryParse。如果要解析字符串,一旦超过初始开发阶段,就应该始终使用TryParse。

理想情况下,验证/输入的评估不允许错误的输入(如数字上升/下降Ken Tucker指出。

如果你以某种方式缺乏对TryParse的访问权限,我写了一份回复:

//Parse throws ArgumentNull, Format and Overflow Exceptions.
//And they only have Exception as base class in common, but identical handling code (output = 0 and return false).

bool TryParse(string input, out int output){
  try{
    output = int.Parse(input);
  }
  catch (Exception ex){
    if(ex is ArgumentNullException ||
      ex is FormatException ||
      ex is OverflowException){
      //these are the exceptions I am looking for. I will do my thing.
      output = 0;
      return false;
    }
    else{
      //Not the exceptions I expect. Best to just let them go on their way.
      throw;
    }
  }

  //I am pretty sure the Exception replaces the return value in exception case. 
  //So this one will only be returned without any Exceptions, expected or unexpected
  return true;

}