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

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

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,以便在每次点击时都是黑色的.在表单的构造函数中将其设置为黑色.

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...