2016-04-21 42 views
1

我試圖讓標籤增加1,每個按鈕點擊5,然後恢復到1,然後重新開始。但是,我似乎錯誤地輸入了我的for循環。任何人都可以指出我要出錯的地方嗎?對C#很新穎。按鈕上的標籤增量單擊使用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(); 
    } 
} 

-The標籤文本默認爲1

謝謝

+0

無法看到您的標籤更改其文本。只有在您退出事件處理程序後纔會更新標籤。 – Steve

+0

循環的目的是什麼?迭代速度如此之快,你不會在視覺上看到它。 – Alex

+0

沒有指向循環,只需使用1開始的grobal變量,並且每次用戶單擊該按鈕時,只需將該變量添加到1,或者如果值爲6,則重置該變量, – NomNomNom

回答

3

當單擊該按鈕,您更改值的標籤,遞增其當前值。
此解決方案使用的% 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(); 
    } 
} 



解釋%運算符
在這種情況下
因此,「%運算符通過其第二分割其第一個操作數後計算餘數」結果將是:

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 
+0

非常感謝。我刪除了for循環。我忽略了它不會在每個增量之間停頓。這工作很好,減去它重置爲0而不是1. – Jret

+0

@ sploosh4snootch是的,我的壞!我寫了錯誤的算法...但後來我編輯了我的答案,現在應該做的工作 –

+0

我的歉意。我清醒之前回復,看看你的編輯。再次感謝!完美的作品。 – Jret

0

如果我理解你想要什麼:

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

最有可能你將需要標籤的價值爲您的業務邏輯 - 下注。我認爲你應該有一個私人變量,從按鈕onclick事件中增加它,然後將其複製到標籤文本框中。

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

試試這個:

int bet = 1; 

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

     if (bet == 6) 
      bet = 1;     

     lblBet.Text = bet.ToString(); 
    } 

投注變量需要的功能之外聲明。

0

你可以試試這個:

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

無需for循環。初始化按鈕點擊之外的賭注:

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


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

}