Я предлагаю поставить 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
}