sploosh4snootch sploosh4snootch - 9 months ago 59
C# Question

Label Increment on Button Click with For Loop C#

I am trying to get a label to increase by 1 with each button click up to 5 then revert back to 1 and start again. However, I seem to be entering my for loop incorrectly. Could anyone point out where I'm going wrong? Very new to C#.

private void bttnAdd_Click(object sender, EventArgs e)
{
int bet = 1;
if (bet < 6)
{
for (int bet = 1; bet <= 6; bet++)
{
lblBet.Text = "" + bet;
}
}
else
{
lblBet.ResetText();
}
}


-The label text is defaulted to 1.

Thank you

Answer Source

When the button is clicked, you change the value of the label, incrementing its current value.
This solution uses the % Operator (C# Reference)

private void bttnAdd_Click(object sender, EventArgs e)
{
    int currentValue;
    // Tries to parse the text to an integer and puts the result in the currentValue variable
    if (int.TryParse(lblBet.Text, out currentValue))
    {
        // This equation assures that the value can't be greater that 5 and smaller than 1
        currentValue = (currentValue % 5) + 1;
        // Sets the new value to the label 
        lblBet.Text = currentValue.ToString();
    }
}



Explaining the % operator
"The % operator computes the remainder after dividing its first operand by its second"
So in this case the results will be:

int currentValue = 1;
int remainderCurrentValue = currentValue % 5; // Equals 1
int increasedCurrentValue = remainderCurrentValue + 1; // Equals 2

And when the current value is 5 this is going to happen:

int currentValue = 5;
int remainderCurrentValue = currentValue % 5; // Equals 0
int increasedCurrentValue = remainderCurrentValue + 1; // Equals 1