[英]How to take only single label,radio button for every increment in a loop for window form 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.