The first thing to do is to set a break-point and single-step through this code, and observe at what point NaN "exists."
Second, you are using Convert.ToDouble which will return a result of #0 if the conversion fails ... I don't think that's too useful; what if zero is a valid entry for one TextBox, but not a valid entry for another ? I strongly recommend you use Double.TryParse which will give you a boolean 'false if the conversion is not possible [
^]. You'll see 'TryParse used in the code below.
I believe in a strategy I call "head 'em off at the pass" which translates into: "intercept errors and deal with them as soon as possible." I also mean by this: "do not let users have initiate any action using controls which
depend on valid data
unless the data is valid."
So, for example, I might define a routine for checking all the TextBoxes of interest for valid double values:
public static class MathUtilities
{
public static IEnumerable<double> TextBoxesToDoubles(params TextBox[] args)
{
double dbl;
foreach (TextBox tbx in args)
{
if (! Double.TryParse(tbx.Text, out dbl))
{
throw new ArgumentException(string.Format("contents of {0} are not a valid double", tbx.Name));
}
yield return dbl;
}
}
}
But, before I ever invoked the static method shown above, I would make sure that each TextBox at least had some characters in it:
TextBox[] DoubleInputTextBoxes;
private void button1_Click(object sender, EventArgs e)
{
if (ValidateTextBoxesForDouble())
{
}
}
private bool ValidateTextBoxesForDouble()
{
DoubleInputTextBoxes = new TextBox[]
{
textBox2, textBox3, textBox4, textBox5
};
if(DoubleInputTextBoxes.Any(tbx => tbx.Text == string.Empty))
{
throw new ArgumentException(string.Format("contents of one or more TextBoxes is not a valid double"));
}
List<double> doubles = MathUtilities.TextBoxesToDoubles(DoubleInputTextBoxes).ToList();
return true;
}
The code shown here is just
one way (among many ways) to handle/implement validation of data; I don't claim it's the best fit for your specific task at hand.
In terms of your specific code ... once you know you have valid data in your input TextBoxes ... I'd say you need to write multiple checks as you progress through your calculations, if, at any point, you get a value like a NaN that means you can't get a valid result from your calculations, then stop the code right there, give the user a message, or throw an error.
Other alternatives:
1. use NumericUpDownControls instead of TextBoxes : greatly simplifies things. however, it's true that many people just don't like the "look and feel" of them.
2. create your own sub-classed TextBox (Component) designed for input of Doubles. this is typically what I use.
3. look here on CP for other numeric user input controls.