此代码会立即将文本框更改为红色.我想要它,点击按钮然后红色,然后再绿色.
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; } }
解决方法
如果出现以下情况,您想使用else:
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; }
您正在做的是将其更改为红色,然后检查它是否为红色并将其更改为绿色.通过使用else,如果你是黑色则不执行if.
此外,正如蒂姆在评论中指出的那样,你需要删除行textBox1.BackColor = System.Drawing.Color.Black,以便在每次点击时都是黑色的.在表单的构造函数中将其设置为黑色.