-1

I am learning C# (in Visual Studio Express 2013 for Windows Desktop) by converting a simple Windows Form application I previously wrote in Visual Basic.

The following code sends a text box entry and two integers to a method that returns a boolean, but throws an exception at runtime whenever the text box doesn't contain an integer (e.g 155 is OK, but 155.67 isn't).

if (!(rangeOK(int.Parse(cmTextBox.Text), 50, 250))) return false;

I've tried using TryParse to resolve this, but despite trying lots of online tips (and others' questions in here) I haven't been able to understand how I should do it.

If it helps the original VB code was:

If Not (rangeOK(Val(cmTextBox.Text), 50, 250)) Then Return False

Many thanks

Rob

Optical Race
  • 63
  • 1
  • 7
  • Can you show your `rangeOK` method definition as well? It is not clear what you asking. – Soner Gönül Jan 17 '15 at 09:46
  • `155.67` is *not* an integer. You need to parse the data to `single`, `double` or `decimal`. Then you can try to cast the value to an integer. – Bjørn-Roger Kringsjå Jan 17 '15 at 09:50
  • My RangeOK method is private bool rangeOK(int userEntry, int minima, int maxima) { if ((userEntry >= minima & userEntry <= maxima)) return true; else return false; } – Optical Race Jan 17 '15 at 10:01
  • Thanks Bjorn-Roger, I understand that 155.67 is not an integer and will return false, which is what I want the code to do. Sorry for being unclear on that. – Optical Race Jan 17 '15 at 10:04

1 Answers1

3

This is how you use TryParse:

int result; // does not need to be initialized
if (int.TryParse(cmTextBox.Text, out result))
{
  if (!(rangeOK(result, 50, 250)))
    return false;
  // todo
} else
{
  // process error
}

More information here:

http://msdn.microsoft.com/en-us/library/f02979c7%28v=vs.110%29.aspx

Good luck with it!

UPDATE

You can do the same with double.TryParse of coure, if you want to work with non integer numbers. More information here:

http://msdn.microsoft.com/en-us/library/994c0zb1%28v=vs.110%29.aspx

Gábor Angyal
  • 2,225
  • 17
  • 27