1

Users enter numbers into textboxes, and the values are displayed on a graph. I want to be sure users type numbers in the textboxes, so I tried:

double xValue;
double yValue;

Double.TryParse(xTextBox.Text, out xValue);
Double.TryParse(yTextBox.Text, out yValue);

chart1.Series["data1"].Points.AddXY(xValue, yValue);

Double.TryParse() validates whether users type numbers, but I'm not sure how to code for when users don't type numbers. Double.TryParse() will assign xValue or yValue a 0--but I also want users to be able to enter 0 values so I cannot just code something like

if (xValue!=0 && yValue!=0)...

Something like

if (xTextBox.Text!="0") {
  Double.TryParse(xTextBox.Text, out xValue);
  }

seems like awkward code that will just get more. What's the standard way to make sure users entered a double?

Al C
  • 5,175
  • 6
  • 44
  • 74
  • What do you mean by _but I also want users to be able to enter 0 values_? They actually can. If `Double.TryParse` fails, this method will assing the out parameter to `0`. – Soner Gönül Feb 14 '15 at 21:32

3 Answers3

1

TryParse returns a boolean which is true if the conversion succeeded, and false if it failed.

if (!Double.TryParse(xTextBox.Text, out xValue)) {
     // handle a failure to convert here
}
Douglas Zare
  • 3,296
  • 1
  • 14
  • 21
1

Double.TryParse returns a boolean if parsing was a success, and you should check the results of Double.TryParse not the xValue and yValue.

ig-melnyk
  • 2,769
  • 2
  • 25
  • 35
1

First of all you need to take into consideration the user locale settings. For example in USA the decimal separator is . and in my country it is ,. So you need to specify the format when user enters double values or replace , with . and then parse values with Invariant culture.

Second Double.TryParse method returns bool value which you can use to check whether the entered value is successfully parsed as double.

Nikolay Kostov
  • 16,433
  • 23
  • 85
  • 123
  • 1
    +1 for mentioning invariant culture [http://stackoverflow.com/questions/2423377/what-is-the-invariant-culture] which I did not know about. – Al C Feb 14 '15 at 21:56