Kan*_*iet 3 c# if-statement button
此代码会立即将文本框更改为红色.我想要它,点击按钮然后红色,然后再绿色.
private void button1_Click(object sender, EventArgs e)
{
textBox1.BackColor = System.Drawing.Color.Black;
if (textBox1.BackColor.Equals(System.Drawing.Color.Black))
{
textBox1.BackColor = System.Drawing.Color.Red;
}
if (textBox1.BackColor.Equals(System.Drawing.Color.Red))
{
textBox1.BackColor = System.Drawing.Color.Green;
}
if (textBox1.BackColor.Equals(System.Drawing.Color.Green))
{
textBox1.BackColor = System.Drawing.Color.Blue;
}
if (textBox1.BackColor.Equals(System.Drawing.Color.Blue))
{
textBox1.BackColor = System.Drawing.Color.Red;
}
}
Run Code Online (Sandbox Code Playgroud)
您始终将颜色设置为黑色.
逻辑最终是:
Set the color to black.
Is it black? Yes - change to red.
Is it red? Yes - change to green.
Is it green? Yes - change to blue.
Is it blue? Yes - change to red.
Run Code Online (Sandbox Code Playgroud)
不要那样做.
将初始设置移动到类构造函数,并在设置颜色后立即从函数返回(或使用if/elseif/else构造).
你想使用else if:
if (textBox1.BackColor.Equals(System.Drawing.Color.Black))
{
textBox1.BackColor = System.Drawing.Color.Red;
}
else if (textBox1.BackColor.Equals(System.Drawing.Color.Red))
{
textBox1.BackColor = System.Drawing.Color.Green;
}
else if (textBox1.BackColor.Equals(System.Drawing.Color.Green))
{
textBox1.BackColor = System.Drawing.Color.Blue;
}
else if (textBox1.BackColor.Equals(System.Drawing.Color.Blue))
{
textBox1.BackColor = System.Drawing.Color.Red;
}
Run Code Online (Sandbox Code Playgroud)
你正在做的是将其更改为red,然后检查它是否正确red并将其更改为green.通过使用else if你不会执行if red如果它black.
此外,正如Tim在评论中指出的那样,textBox1.BackColor = System.Drawing.Color.Black如果black每次点击都需要删除该行以停止.将其设置为black表单的构造函数.