在同一文本框中显示更多 true if 语句(Windows Forms app)c#

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

我正在尝试在 windows 表单应用程序中制作一个零钱计算器,我需要在其中显示客户将获得退款的账单。我的问题是文本框只会显示我的 if 语句中的一个值。

例如

如果客户需要返回 644,它只会说 1 500 kr。它应该显示如下: 1 500 钞票 1 100 钞票 2 20 硬币 2 2 硬币。 希望你能帮忙:)

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

您的错误是您用 属性 Text 的新文本覆盖了每个 if 语句中的旧文本。 例如,如果你想将“twos”添加到“ones”,那么你需要写

tbxCashType.Text += twos + " Tvåkronor";

+= 运算符将右侧的字符串添加到现有字符串值中。所以你可以组合多个字符串(concat strings)。

如果你想添加一个完整的新字符串,那么你只需要=。这会覆盖旧值。

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