首页 > 解决方案 > 如何在 C# 中制作一个始终检查文本框条件的程序?

问题描述

我一直想知道如何在 C# 中制作一个程序,始终检查当文本框不包含任何内容时,将文本框的背景颜色变为红色。否则,文本框保持不变。我已经为此编写了代码,但不知道放在哪里。

for (;;)
        {
            if (textBox1.Text == "" && textBox2.Text == "")
            {
                textBox1.BackColor = System.Drawing.Color.Red;
                textBox2.BackColor = System.Drawing.Color.Red;
            }
            if (textBox1.Text != "" && textBox2.Text == "")
            {
                textBox1.BackColor = System.Drawing.SystemColors.Control;
                textBox2.BackColor = System.Drawing.Color.Red;
            }
            if (textBox1.Text == "" && textBox2.Text != "")
            {
                textBox1.BackColor = System.Drawing.Color.Red;
                textBox2.BackColor = System.Drawing.SystemColors.Control;
            }
            if (textBox1.Text != "" && textBox2.Text != "")
            {
                textBox1.BackColor = System.Drawing.SystemColors.Control;
                textBox2.BackColor = System.Drawing.SystemColors.Control;
            }
        }

我也不希望代码处于用户权限之下。(比如说点击一个按钮来检查文本框的情况)

标签: c#user-interface

解决方案


您可以使用事件 textbox_change 或按钮

textbox8 是上部文本框,textbox9 是下部文本框试试这个:

---下面的代码是用于文本更改

 private void TextBox8_TextChanged(object sender, EventArgs e)
    {
        if (TextBox8.Text == "")
            TextBox8.BackColor = Color.Red;
        else
            TextBox8.BackColor = Color.White;
    }

    private void TextBox9_TextChanged(object sender, EventArgs e)
    {
        if (TextBox9.Text == "")
            TextBox9.BackColor = Color.Red;
        else
            TextBox9.BackColor = Color.White;
    }

下面的代码用于按钮:

private void Button2_Click(object sender, EventArgs e)
    {
        if (TextBox8.Text == "")
            TextBox8.BackColor = Color.Red;
        else
            TextBox8.BackColor = Color.White;
        if (TextBox9.Text == "")
            TextBox9.BackColor = Color.Red;
        else
            TextBox9.BackColor = Color.White;
    }

在此处输入图像描述


推荐阅读