0

I'm building a Windows Form in C# and I'm trying to test whether the users input is between 1 and 7 (Representing the number of days in a week, that a movie can be rented). If the test returns false, then I want to output an error message. I'm using a text box to get the users input. The problem is, I keep receiving this error when running the program :

System.FormatException was unhandled

HResult=-2146233033

Message=Input string was not in a correct format.

Can somebody please, tell me what I am doing wrong. Thank you in advance.

Here is the code I have written..

 private void nightsRentedTextBox_TextChanged_1(object sender, EventArgs e)
    {
        Boolean inputBoolean = true;
      
        if (int.Parse(nightsRentedTextBox.Text) < 1)
        {
            MessageBox.Show("Enter a number between 1 and 7", "INPUT ERROR",
            MessageBoxButtons.OK, MessageBoxIcon.Error);
            inputBoolean = false;
        }
1
  • 1
    to start with use TryParse()..... Commented Nov 18, 2016 at 3:25

1 Answer 1

1

You should use TryParse instead.

int nightsRented;
bool res = int.TryParse(nightsRentedTextBox.Text, out nightsRented);
if (res == false)
{
  // String is not a number.
}

or you can use it like

int nightsRented;
if (int.TryParse(nightsRentedTextBox.Text, out nightsRented);)
{
    if (nightsRented >= 1 || nightsRented <= 7)
    {
        MessageBox.Show("Enter a number between 1 and 7", "INPUT ERROR",
        MessageBoxButtons.OK, MessageBoxIcon.Error);
        inputBoolean = false;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Can use if (Enumerable.Range(1, 7).Contains(NumberOfNights)) too.
Happy to help. :) @CaseySmith

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.