Search code examples
c#vb.netvisual-studio-express

C# parsing integer from text box correctly


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


Solution

  • 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