簡體   English   中英

按鈕上的標簽增量單擊For循環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。

謝謝

單擊該按鈕時,您可以更改標簽的值,增加其當前值。
此解決方案使用%運算符(C#參考)

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();
    }
}



解釋%運算符
“%運算符在將第一個操作數除以第二個操作數后計算余數”
所以在這種情況下,結果將是:

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

如果我明白你想要的:

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

您很可能需要為您的業務邏輯提供標簽的價值 - 下注。 我認為你應該有一個私有變量,從按鈕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();
   }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM