Home > OS >  display more true if statements in the same textbox ( Windows Forms app) c#
display more true if statements in the same textbox ( Windows Forms app) c#

Time:02-26

I'm trying to make a change calculator in windows forms app where i need to show in what bills the customer will get money back. My problem is that the textboxt only will show one value from my if statements.

e.g

if the customer needs 644 back it only says 1 500 kr. where it was supposed to show like: 1 500 bill 1 100 bill 2 20 coin 2 2 coin. Hope you can help :)

public void cashCalculator() {

        fiveHundreds = exchange / 500;
        remainder = exchange % 500;

        twoHundreds = remainder / 200;
        remainder = remainder % 200;

        hundreds = remainder / 100;
        remainder = remainder % 100;

        fiftys = remainder / 50;
        remainder = remainder % 50;

        twenties = remainder / 20;
        remainder = remainder % 20;

        tens = remainder / 10;
        remainder = remainder % 10;

        fives = remainder / 5;
        remainder = remainder % 5;

        twos = remainder / 2;
        remainder = remainder % 2;

        ones = remainder;

        // if statements to sort out what cashtype that will be shown in lblCashType:

        

        if (ones >0)
        {
            tbxCashType.Text = ones   " Enkronor";   
            
            
        }
        
      if (twos > 0)
        {
            
            tbxCashType.Text = twos   " Tvåkronor";
            
        }

      if (fives > 0)
        {
            tbxCashType.Text = fives   " Femkronor";
            
        }

      if (tens > 0)
        {
            tbxCashType.Text = tens   " Tikronor";
            
        }


      if (twenties > 0)
        {
            tbxCashType.Text = twenties   " Tjugolapp";
            
        }

      if (fiftys > 0)
        {
            tbxCashType.Text = fiftys   " Femtiolapp";
            
        }

      if (hundreds > 0)
        {
            tbxCashType.Text = hundreds   " Hundralapp";
            
        }

     if (twoHundreds > 0)
        {
            tbxCashType.Text = twoHundreds   " Tvåhundralapp";
            
        }


        if (fiveHundreds > 0)
        {
            tbxCashType.Text = fiveHundreds   " Femhundralapp";
            
        } 

CodePudding user response:

Your mistake is that you overwrite the old text in every if statement with the new text for the property Text. For instance, if you want to add the "twos" to the "ones", than you need to write

tbxCashType.Text  = twos   " Tvåkronor";

The = operator adds the string on the right side to the existing string value. So you can combine multiple strings (concat strings).

If you want to add a complete new string, then you only need =. This overwrites old values.

See C# docs: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/addition-operator#addition-assignment-operator-

  • Related