Search code examples
c#winformsdatetimetextdouble

loop in GUI, displaying n times


In the following code within the button method, when 'work hours' are more than 40, the program need to display “Bonus!” three time on the Form.

my question is ... instead of simple if statement, how do we use loop (for loop/ while loop the easiest way) in this form here?

I'm just wondering what is the simplest form of loop when it comes to displaying a message more than one time.

Thanks a lot, Alex Del

double hrsWorked;
double payRate, Salary;
hrsWorked = Convert.ToDouble(textBox1.Text);
payRate = Convert.ToDouble(textBox2.Text);
Salary = hrsWorked * payRate;

//need to use a loop (either for loop or while loop saying if no. hours is more than 40 (41, 42, 43, ...) 
//shows 'Bonus' three times and when recalculate for any keyed in input again shows 3 times 'Bonus' before its Calculation as shown in the expected output image.





//if (hrsWorked > 40)
//{
//    label3.Text = "Bonus";
//    label4.Text = "Bonus";
//    label5.Text = "Bonus";
//}

label6.Text = "calculated amount is " + Salary;

enter image description here


Solution

  • Count DOWN to 40 from your current # of work hours, and use a multiline text box or a label with wrapping:

    StringBuilder sbResults = new StringBuilder();
    for(double i = num1; i  > 40; i--)
    {
       // Each loop iteration here is one hour over 40 hours
       sbResults.AppendLine("Bonus!");
    }
    YourMultilineControl.Text = sbResults.ToString();
    

    If you want just one line for every 10 hours over, then change i-- to i -= 10.

    On a side note, you should really get into the habit of immediately giving things good names. Don't post questions here with "num1” and "TextBox1" and "label3" names - it's impossible to know for sure what those are referring to when looking at the code. Instead, use "numWorkHours" and "txtWorkHours" and so on.

    Oh and one last note - a loop probably isn't the most efficient way of doing this. Subtract total hours - 40 to find the number of hours over 40 and then use that number to repeat a string as many times as necessary.