使用 For 循环 C# 单击按钮时标签递增
本文关键字:标签 按钮 单击 For 循环 使用 | 更新日期: 2024-10-24 23:24:30
我试图让标签增加 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();
}
投注变量需要在函数外部声明。
不需要 for 循环。在按钮点击之外初始化投注:
int bet = 1;
private void bttnAdd_Click(object sender, EventArgs e)
{
if (bet <= 6)
{
this.bet++;
lblBet.Text = bet.toString();
}
}
你可以试试这个:
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;
}
}