Search code examples
c#windows-phone-8visual-studio-2013windows-phone-8-sdk

How to validate the TextBox correctly in C#?


I am new to C#, I am having a problem with TextBox validating grade letters (A, B, C, D, F). Right now, this code below will do the if statement and not the else statement as it supposed to if I input a grade letter exactly matching its condition, even if lower cased and then upper cased after clicking the OK button. When I input a correct grade letter, it should skip the if and proceed to the else statement, but something is wrong that I'm not seeing.

    private void Button_Click(object sender, RoutedEventArgs e)
    {

        //automatically convert gradeLetter inputs to uppercase
        gradeLetter.Text = gradeLetter.Text.ToUpper();

        //check if gradeLetter entered is valid
        if (!string.IsNullOrWhiteSpace(gradeLetter.Text) || gradeLetter.Text != "A" || gradeLetter.Text != "B" || gradeLetter.Text != "C" || gradeLetter.Text != "D" || gradeLetter.Text != "F")
        {
            MessageBox.Show("Invalid grade letter or has an empty textbox!", "Caution!", MessageBoxButton.OK);
        }
        else
        {
            // switch statement to determine which 'gradeLetter' is being used 
            // and assign numerical numbers to 'gpa' to then be calculated.
            switch (gradeLetter.Text)
            {
                case "A": gradeW = 4.0;
                    break;
                case "B": gradeW = 3.0;
                    break;
                case "C": gradeW = 2.0;
                    break;
                case "D": gradeW = 1.0;
                    break;
                case "F": gradeW = 0.0;
                    break;
                default: // do nothing
                    break;
            }

            double result = (GPA += gradeW); //add to the gpa
            gCounter++; // increment the gpa entered
            result /= gCounter; // divide by the number of gpa entered
            result = Math.Round(result, 2, MidpointRounding.AwayFromZero); //round the result to two decimal places

            gpa.Text = result.ToString(); //convert result from int to string and display in 'gpa' TextBlock

            //append the input grade letters to 'gradeEntered' TextBlock
            gradeEntered.Text += gradeLetter.Text + System.Environment.NewLine;
       }
    }

Solution

  • The problem with your current if statement is that valid input will still come up as invalid. If the input is "B", it will see that it is not "A" (which is in your if statement) which means the whole criteria is then true.

    Change your if statement to this:

    if (string.IsNullOrWhiteSpace(gradeLetter.Text) || !(gradeLetter.Text == "A" || gradeLetter.Text == "B" || gradeLetter.Text == "C" || gradeLetter.Text == "D" || gradeLetter.Text == "F"))
    

    which essentially asks "Is your input empty or is your input not A,B,C,D, or F?