我有一个带有各种小程序的wpf应用程序,其中一个计算平行四边形的面积。我正在添加一些错误处理,以便如果用户在高度或宽度框中输入大于double.MaxValue
的值,则会显示错误消息。如何确定哪个文本框输入触发了异常,以便将其与错误消息一起返回?如果重要,则“高度”和“宽度”框位于“用户控件”中。
private void AreaOfParallelogramCalcBtn_Click(object sender, RoutedEventArgs e)
{
if (Convert.ToDouble(AreaOfParallelogramHeightTxtBox.Text) > double.MaxValue == false || (Convert.ToDouble(AreaOfParallelogramWidthTxtBox.Text) > double.MaxValue == false))
{
MessageBox.Show("Seriously? That is a pretty big number. Please try again.");
}
else
{
AreaOfParallelogramResultTxtBox.Text =
CalculateAreaOfParallelogram.Calculate(Convert.ToDouble(AreaOfParallelogramHeightTxtBox.Text),
Convert.ToDouble(AreaOfParallelogramWidthTxtBox.Text)).ToString();
}
}
答案 0 :(得分:0)
所以这可能不是最好的方法,但这就是我最终做的并取得了预期的效果。
private void AreaOfParallelogramCalcBtn_Click(object sender, RoutedEventArgs e)
{
if (Convert.ToDouble(AreaOfParallelogramHeightTxtBox.Text) > 25000000)
{
MessageBox.Show($"Height input out of range. Height must be less than 25,000,000\n{Convert.ToDouble(AreaOfParallelogramHeightTxtBox.Text):n0} is a pretty big number. Please try again.", "*WARNING*", MessageBoxButton.OK, MessageBoxImage.Warning);
}
else if (Convert.ToDouble(AreaOfParallelogramWidthTxtBox.Text) > 25000000)
{
MessageBox.Show($"Width input out of range. Width must be less than 25,000,000\n{Convert.ToDouble(AreaOfParallelogramWidthTxtBox.Text):n0} is a pretty big number. Please try again.", "*WARNING*", MessageBoxButton.OK, MessageBoxImage.Warning);
}
else
{
AreaOfParallelogramResultTxtBox.Text =
CalculateAreaOfParallelogram.Calculate(Convert.ToDouble(AreaOfParallelogramHeightTxtBox.Text),
Convert.ToDouble(AreaOfParallelogramWidthTxtBox.Text)).ToString(CultureInfo.InvariantCulture);
}
}
答案 1 :(得分:0)
使用例外来源
try
{
....
}
Catch(Exception ex)
{
MessageBox.Show(ex.Source)
}