使用 For Loop C# 在按钮上单击标签增量

Label Increment on Button Click with For Loop C#

我正在尝试让标签增加 1,每次单击按钮最多 5 次,然后恢复为 1 并重新开始。但是,我似乎错误地输入了我的 for 循环。谁能指出我哪里出错了?对 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();
    }
}

-标签文字默认为1。

谢谢

如果我明白你想要什么:

int bet = 1;
bool increase=true;
private void bttnAdd_Click(object sender, EventArgs e)
{
   if(increase){
      bet++;
      lblBet.Text = "" + bet;
   }
   else{
       bet--;
       lblBet.Text = "" + bet;
   }
   if(bet==5 || bet==1)
   {
       increase=!increase;
   }
}

单击按钮时,您更改标签的值,增加其当前值。
此解决方案使用 % 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();
    }
}



解释 % 运算符
"The % operator computes the remainder after dividing its first operand by its second"
所以在这种情况下,结果将是:

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

当当前值为 5 时,将发生以下情况:

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

您的业务逻辑很可能需要标签的值 - 来下注。我想你应该有一个私有变量,从按钮的 onclick 事件中增加它,然后将它复制到标签文本框中。

            private void bttnAdd_Click(object sender, EventArgs e)
            {
                int bet = int.Parse(lblBet.Text);
                lblBet.Text = bet<5 ? ++bet : 1;
            }

试试这个:

    int bet = 1;

    private void button1_Click(object sender, EventArgs e)
    {
        bet++;

        if (bet == 6)
            bet = 1;                

        lblBet.Text = bet.ToString();
    }

Bet 变量需要在函数外声明。

你可以试试这个:

static int count=0;// Global Variable declare somewhere at the top 

protected void bttnAdd_Click(object sender, EventArgs e)
        {
            count++;

            if (count > 6)
            {
                lblBet.Text = count.ToString();
            }
            else
            {
                count = 0;
            }
        }

不需要 for 循环。在按钮点击之外初始化投注:

int bet = 1;
private void bttnAdd_Click(object sender, EventArgs e)
{


   if (bet <= 6)
   {
       this.bet++;
       lblBet.Text = bet.toString();
   }

}