获取导致FormatException的文本框

时间:2018-05-04 12:04:09

标签: c# winforms

我有这段代码:

try 
{
    n1 = Convert.ToSingle(textBoxN1.Text); 
    n2 = Convert.ToSingle(textBoxN2.Text);
}
catch (FormatException e)
{
    MessageBoxShow("...");
}

是否可以让消息框显示哪个textBox导致FormatException?

编辑: 不幸的是,我必须使用FormatException,因为它是家庭作业的一部分,我们不得不使用FormatException。

3 个答案:

答案 0 :(得分:4)

我建议将float.TryParse放入if

if (!float.TryParse(textBoxN1.Text, out n1))
  MessageBoxShow("textBoxN1 has incorrect value");
else if (!float.TryParse(textBoxN2.Text, out n2))
  MessageBoxShow("textBoxN2 has incorrect value");
else {
  // Both textboxes are correct; n1 and n2 are parsed values
}

修改:如果您必须使用FormatException,请尝试以最舒适的方式进行操作:让我们提取方法

private static bool TextBoxToSingle(Control control, string message, out float result) {
  float result = float.NaN;

  try {
    result = Convert.ToSingle(control.Text);

    return true;
  }
  catch (FormatException) { // we don't want "e" here
    MessageBoxShow(message);

    return false; 
  }  
}

...

if (TextBoxToSingle(textBoxN1.Text, "textBoxN1 has incorrect value", out n1) && 
    TextBoxToSingle(textBoxN2.Text, "textBoxN2 has incorrect value", out n2)) {
  // Both textboxes are correct; n1 and n2 are parsed values
}

答案 1 :(得分:1)

您可以使用MessageBoxe.ToString()上显示所有堆栈跟踪。此字符串将显示哪行代码导致异常。尝试:

catch (FormatException e)
{
    MessageBoxShow(e.ToString());
}

答案 2 :(得分:1)

如果你必须像评论(家庭作业)那样使用try...catch方法,那么你必须连续使用两个try...catch并确定哪个失败了,或者使用它:

float n1 = Single.NaN; // or a different default value
float n2 = Single.NaN; // or a different default value

try
{
    n1 = Convert.ToSingle(textBoxN1.Text);
    n2 = Convert.ToSingle(textBoxN2.Text);
}
catch (FormatException e)
{
    TextBox errorBox = n1 == Single.NaN ? textBoxN1 : textBoxN2;
    MessageBoxShow("This TextBox caused a FormatException: " + errorBox.Name);
}