C# 按长度更改 txtBox BackColor

标签 c# winforms background textbox

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

我想更改用户键入姓名的 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;
        }

    }
}
}

最佳答案

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

关于C# 按长度更改 txtBox BackColor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27705031/

相关文章:

C# System.NullReferenceException 错误谷歌日历

c# - 运行时类型转换

c# - TCP 套接字连接

c# - 使用组合框显示工具提示(下拉菜单)

c# - 使用带有窗口窗体的 iTextSharp 创建 pdf

linux - 防止在子 shell 中调用 bash 函数的输出

c# - TextBox 上的 AcceptsReturn 无法正常运行

c# - 将 MenuItem 添加到控制台应用程序中 TrayIcon 的上下文菜单

ios - swift 3+,URLsession,在后台明显随机失败

windows-8 - 如何使用javascript取消Windows 8.1中的后台任务