Casey Smith Casey Smith - 19 days ago 7
C# Question

How to test if an Integer is within a range while using a TextBox in C#

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;
}

Answer

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;
    }
}