此代码会立即将文本框更改为红色.我想要它,点击按钮然后红色,然后再绿色

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)

Ode*_*ded 8

您始终将颜色设置为黑色.

逻辑最终是:

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构造).

  • @ user1803685 - 但是你在_every_按钮点击时执行此操作.您应该在构造函数中初始化它.你这样做的方式,颜色永远不会循环. (2认同)
  • @ user1803685:使用Visual Studio中的"属性"窗格将初始文本框颜色设置为黑色.您不需要将第一行设置为黑色,甚至不需要在构造函数中.正如Dave Shaw所指出的,你需要`else``if`'s. (2认同)

Dav*_*haw 6

你想使用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表单的构造函数.

  • 到目前为止,你的答案是最有帮助的,但正如其他人所指出的那样,最初将颜色设置为黑色只会导致第一个条件被触发. (2认同)