Jan
Jan

Reputation: 27

If number is between X and Y

I am trying to create a simple Windows Form Application (Visual Studio 2013) to convert a (school)grade into text e.g. enter 1 -> "very good" and so on.

private void btn_note_Click(object sender, EventArgs e)
{
      if (txtb_note.Text == "1")
      {
           lbl_ergebnis.Text = "very good";
      }

      if (txtb_note.Text == "2")
      {
           lbl_ergebnis.Text = "good";
      } 

      // Etc...
}

and so on. But I want to add that if I type in 99 or just some text it should show "invalid input" for example.

But how could I do that? I´ve tried

if (txtb_note.Text == "?????")
{
      if (txtb_note.Text == "1")
      {
          lbl_ergebnis.Text = "very good";
      }
}
else 
{
    lbl_ergebnis.Text = "invalid";
}

for ????? I need something that says "number between 1 and 6", so a 7 would result in "invalid". What can I use there?

Hope you understand my problem.

BTW: I am pretty new to C# and Visual Studio...

Upvotes: 1

Views: 415

Answers (7)

Jcl
Jcl

Reputation: 28272

Although the other answers show ways of doing it. I'd advise against them, and I'd use the right tools.

What you want, conceptually, is a Dictionary that translates the grades (an integer), to a string, so I'd go that route:

  // We are going to use integer keys, with string values
  var stringGrades = new Dictionary<int, string>()
  {
    {1, "good"}, // 1 is the Key, "good" is the Value
    {2, "decent"},
    {3, "bad"}
  };

  int integerGrade;
  string textGrade;
    // try to convert the textbox text to an integer
  if(!Int32.TryParse(txtb_note.Text, out integerGrade) 
    // if successful, try to find the resulting integer 
    // (now in "integerGrade") among the keys of the dictionary
     || !stringGrades.TryGetValue(integerGrade, out textGrade))
     // Any of the above conditions weren't successful, so it's invalid
     lbl_ergebnis.Text = "Invalid value";
  else
     // It worked, so now we have our string value in the variable "textGrade"
     // obtained by the "out textGrade" parameter on TryGetValue
     lbl_ergebnis.Text = textGrade;

In your specific case, you are using the original grade as a string from a textbox, so go that route if you prefer:

  // This time, we directly use string as keys
  var stringGrades = new Dictionary<string, string>()
  {
    {"1", "good"},
    {"2", "decent"},
    {"3", "bad"}
  };

  string textGrade;
  // Try to get the value in the dictionary for the key matching the text
  // on your textbox, no need to convert to integer
  if(!stringGrades.TryGetValue(txtb_note.Text, out textGrade))
     lbl_ergebnis.Text = "Invalid value";
  else
     lbl_ergebnis.Text = textGrade;

Since TryGetValue and out parameters could be confusing, here's another way to do it, which might be easier to read if you are new to programming (we'll use the same <string, string> dictionary as above):

  // If our dictionary doesn't contain the key we are looking for,
  // the input is invalid
  if(!stringGrades.ContainsKey(txtb_note.Text))
     lbl_ergebnis.Text = "Invalid value";
  else
     // it contains the key, so let's show its value:
     lbl_ergebnis.Text = stringGrades[txtb_note.Text];

Which, if you wanna loop the loop, could be translated to a single line of code, like:

  lbl_ergebnis.Text = stringGrades.ContainsKey(txtb_note.Text) ?
      stringGrades[txtb_note.Text] : "Invalid value";

(don't get confused by this last code, as I said, that's just "looping the loop")

The other ways (using switch or if-else) work, but are not the right tool. Think conceptually, and what you want to do is translate a value to a different value: that's a dictionary, and has a corresponding tool in .NET (the Dictionary<T,T2> class)

If you, in the future, need other grades, you can just add them to the dictionary, and the code converting the strings would keep working. Also, that dictionary doesn't need to be stored in the code: it could be retrieved from a text file, a web service, a database, or whatever, and then it'd work without even recompiling your application.

Upvotes: 2

Ali Vojdanian
Ali Vojdanian

Reputation: 2111

It's simple. Try this :

private void btn_note_Click(object sender, EventArgs e)
    {
        try
        {
            int score = int.Parse(txtb_note.Text);
        if (score >=1 && score <7)
        {
            if (score == 1)
            {
                lbl_ergebnis.Text = "very good";
            }
            .
            .
            .
            // Keep going to 6 
        }
        else
        {
            lbl_ergebnis.Text = "invalid";
        }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

Also you can use switch for that.

private void btn_note_Click(object sender, EventArgs e)
    {
        try
        {
            int score = int.Parse(txtb_note.Text);
        switch (score)
        {
            case "1":
                score = "Very Good";
                break;
            case "2":
                score = "Good";
                break;
                .
                .
                .
                .
                // Keep going to 6 
            default:
                score = "invalid";
                break;
        }
        return score;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

Upvotes: 0

Patrick
Patrick

Reputation: 736

Have you tried a switch statement? like so

        string result;
        switch (txtb_note.Text)
        {
            case "1":
                result = "Very Good";
                break;
            case "2":
                result = "Good";
                break;
            case "3":
                result = "Normal";
                break;
            case "4":
                result = "Below Normal";
                break;
            case "5":
                result = "If you were Asian you would be dishonored";
                break;
            default:
                result = "Invalid Number";
                break;
        }
        return result;

this way everything that is not set in those cases will fall into the default and return "Invalid number"

Upvotes: 1

T&#249;ng Trịnh
T&#249;ng Trịnh

Reputation: 75

You should think about the logic. 1. Convert the textbox value to an integer number. 2. Compare the number to 1 and 7

int value = 0;
//TryParse returns true if the string can be converted to integer and converts the string to integer and pass to variable "value"
if(Integer.TryParse(txtb_note.Text, out value)) 
{
   if(value > 1 && value < 7)
         lbl_ergebnis.Text = "very good";
else lbl_ergebnis.Text = "invalid";
}
else lbl_ergebnis.Text = "invalid";

Upvotes: 0

juharr
juharr

Reputation: 32276

You could just use a if-else if-else

if (txtb_note.Text == "1")
{
    lbl_ergebnis.Text = "very good";
}
else if (txtb_note.Text == "2")
{
    lbl_ergebnis.Text = "good";
} 
else
{
    lbl_ergebnis.Text = "invalid";
}

Or a switch

switch(txtb_note.Text)
{
    case "1":
        lbl_ergebnis.Text = "very good";
        break;
    case "2":
        lbl_ergebnis.Text = "good";
        break;
    default:
        lbl_ergebnis.Text = "invalid";
        break;
}

Then you should also consider parsing the string to an int to allow other options.

int val;
if(!int.TryParse(txtb_note.Text, out val)
{
    lbl_ergebnis.Text = "Not a valid integer";
}
else
{
    if(val >= 0 && val <=4)
        lbl_ergebnis.Text = "Bad";
   // Additional conditions.
}

Upvotes: 1

Sasha
Sasha

Reputation: 1724

First you need to convert it into an int! Try something like this perhaps.

try{
int gradeNumber = int.Parse(txtb_note.Text);
if(gradeNumber > 6) MessageBox.Show("Please enter a number between 1 and 6!");
else if(gradeNumber == 1) lbl_ergebnis.Text = "very good";
else if(gradeNumber == 2) lbl_ergebnis.Text = "good";
// and so on :)
}
catch(Exception){
MessageBox.Show("please enter a valid int!");
}

Upvotes: 0

happybai
happybai

Reputation: 1

you can use “if...else” or "switch" for example

 if (txtb_note.Text == "1")
 {
    lbl_ergebnis.Text = "very good";
 }
 else if (txtb_note.Text == "2")
 {
    lbl_ergebnis.Text = "good";
 }
 ...
 else
 {
     lbl_ergebnis.Text = "invalid";
 }

Upvotes: 0

Related Questions