我一直想知道如何在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;
}
}
我也不希望代码受用户授权。 (例如,单击按钮可检查文本框的状态)
答案 0 :(得分:0)
您可以使用事件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;
}