If Else If Statement in C#

Problem:

Create a program in C# that utilizes if else if statement.

Tutorial Description:

We will create a simple program in c# that will allow the user to enter its grade in the textbox. The user will then click the button to determine the equivalent of that grade in letters.

Ex: the grade is 96, and the value or mark of that grade is A.

The program will determine the value of your grade using the if else if statement.

We will be using Window Form Application in C#. It is used to develop a graphical user interface.

Let’s begin the tutorial:

  1. Open your Microsoft Visual Studio 2010.
  2. Select File then New Project.
  3. Select C# then Windows Form Application and click OK.
  4. We will need the following controls:
    1. 1 label
    2. 1 textbox
    3. 1 button
      c#ifelse1

             Example form design

  1. Double click the button. It will look like this.
private void button1_Click(object sender, EventArgs e)
{

}
  1. Paste the code below between the { } open and close bracket
if (textBox1.Text == "")
{
MessageBox.Show("enter a score from 1 to 100");
textBox1.Focus();
}
else if (double.Parse(textBox1.Text) > 95 && double.Parse(textBox1.Text) <= 100)
{
MessageBox.Show("equivalent is A");
}
else if (double.Parse(textBox1.Text) >= 90 && double.Parse(textBox1.Text) <= 94)
{
MessageBox.Show("equivalent is A-");
}
else if (double.Parse(textBox1.Text) >= 87 && double.Parse(textBox1.Text) <= 89)
{
MessageBox.Show("equivalent is B+");
}
else if (double.Parse(textBox1.Text) > 83 && double.Parse(textBox1.Text) <= 86)
{
MessageBox.Show("equivalent is B-");
}
else if (double.Parse(textBox1.Text) >= 80 && double.Parse(textBox1.Text) <= 83)
{
MessageBox.Show("equivalent is B");
}
else if (double.Parse(textBox1.Text) >= 75 && double.Parse(textBox1.Text) <= 79)
{
MessageBox.Show("equivalent is C");
}
else if (double.Parse(textBox1.Text) < 75)
{
MessageBox.Show("equivalent is F");
}

Code Explanation:

The user must enter a grade before clicking the button or else a message box will appear to notify the user that he or she must enter a grade from 1 to 100. If your grade is greater than 95 the equivalent is A, 90 to 94 is A-, 87 to 89 is B+, 84 to 86 is B-, 80 to 83 is B, 75 to 79 is C and less than 75 is F.

Note: you can also set your own range and value for this program.

  1. Save and Test the project.

c#ifelse2
Download

, , , , ,

Post navigation