C# 按长度更改 txtBox 背景颜色

本文关键字:txtBox 背景 颜色 | 更新日期: 2023-09-27 18:35:36

我想写一个简单的"注册/登录"程序,只是为了我,只是为了好玩。

我想更改用户键入其名称的 TxtBox 的颜色。txtBox.Length<4时,它应将其背景更改为红色。

我不知道为什么我下面的代码不起作用。当我将 txtBox 属性中的文本更改为 5 个以上时,它开始时是蓝色的,但之后不会更改。

我的代码 :

  using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace _4Fun
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            if (regTxtBoxName.TextLength<4) {
                regTxtBoxName.BackColor = Color.Red;
            }
            else{
                regTxtBoxName.BackColor = Color.DarkBlue;
            }
        }
    private void Form1_Load(object sender, EventArgs e)
    {
    }
    private void regBtn_Click(object sender, EventArgs e)
    {
        if (regTxtBoxName.TextLength < 4)
        {
            txtBoxStatus.Text = "Choose a name with minimal length 5. "; // Urobit txtboxname a pass v registru červene pozadie ak x<4
        }
        else {
            txtBoxStatus.Text = "Your account has been successfully created.";
            string name = regTxtBoxName.Text;
        }
        if (regTxtBoxPass.TextLength < 4)
        {
            txtBoxStatus.Text = txtBoxStatus.Text + "Choose password with minimal length 5. ";
        }
        else {
            txtBoxStatus.Text = "Your account has been successfully created.";
            string pass = regTxtBoxPass.Text;
        }
    }
}
}

C# 按长度更改 txtBox 背景颜色

您的代码正在窗体的构造函数中设置颜色,然后您不会更改它。您需要注册以TextChanged TextBox上的事件,以便在应用程序运行时根据Textbox中的字符数更改颜色。

处理文本框 TextChanged 事件,并将此代码放在其中,而不是在构造函数中:

if (regTxtBoxName.TextLength<4) {
    regTxtBoxName.BackColor = Color.Red;
}
else{
    regTxtBoxName.BackColor = Color.DarkBlue;
}
您可以在

Textbox TextChanged 事件中执行此操作。这是代码

void textBox1_TextChanged(object sender, EventArgs e)
{
  if (textBox1.TextLength<4) 
  {
      textBox1.BackColor = Color.Red;
  }
  else
  {
     textBox1.BackColor = Color.DarkBlue;
   }
}

当您在文本框中输入文本时TextChanged事件将调用。 查看此链接 http://www.dotnetperls.com/textchanged

您可能

希望将regBtn_Click方法更改为regBtnTextChanged 。这样,文本框的颜色将在运行时更改。

所以代码将是:

private void regBtnTextChanged(object sender, EventArgs e)
    {
        if (regTxtBoxName.TextLength<4) {
            regTxtBoxName.BackColor = Color.Red;
        }
        else{
            regTxtBoxName.BackColor = Color.DarkBlue;
        }
    }