You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# Winform如何判断变更TextBox与数组内其他文本框值是否重复

C# Winform 文本框重复值校验优化方案

核心实现思路

  • 直接使用TextChanged事件的sender参数获取触发本次变更的文本框实例,无需全量遍历定位变更对象
  • 校验时仅对比当前变更文本框与数组内其他文本框的值,大幅减少无效遍历

前置操作

先在窗体构造函数中批量绑定所有文本框的TextChanged事件,无需手动逐个绑定:

public Form1()
{
    InitializeComponent();
    // 原有给textBoxArray赋值的代码保持不变
    textBoxArray[0, 0] = textBox1;
    // ... 中间的赋值代码保持不变
    textBoxArray[4, 4] = textBox25;
    
    // 新增:批量绑定TextChanged事件
    for (int i = 0; i < 5; i++)
    {
        for (int j = 0; j < 5; j++)
        {
            textBoxArray[i, j].TextChanged += ifTextChanged;
        }
    }
}

优化后的事件处理代码

替换原有ifTextChanged方法逻辑即可:

private void ifTextChanged (object sender, EventArgs e)
{
    // 拿到当前触发文本变更的文本框
    TextBox currentTextBox = sender as TextBox;
    if (currentTextBox == null) return;

    // 原有逻辑优化:仅处理当前文本框的只读设置,无需全量遍历
    if (currentTextBox.Text.Equals("1"))
    {
        currentTextBox.ReadOnly = true;
    }

    // 空值不需要做重复校验,可根据需求调整
    if (string.IsNullOrWhiteSpace(currentTextBox.Text))
    {
        return;
    }

    // 仅对比当前文本框和其他所有文本框的值
    bool hasDuplicate = false;
    for (int i = 0; i < 5; i++)
    {
        for (int j = 0; j < 5; j++)
        {
            // 跳过当前正在输入的文本框
            if (textBoxArray[i, j] == currentTextBox)
            {
                continue;
            }
            // 匹配到重复值
            if (textBoxArray[i, j].Text.Equals(currentTextBox.Text))
            {
                hasDuplicate = true;
                break;
            }
        }
        if (hasDuplicate) break;
    }

    // 存在重复值时展示错误提示
    if (hasDuplicate)
    {
        // 可替换为ErrorProvider控件实现更友好的行内提示
        MessageBox.Show("输入值已存在,请重新输入!", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        // 可选:选中当前输入内容方便直接修改
        currentTextBox.SelectAll();
    }
}

补充说明

如果需要更友好的错误提示,可在窗体中添加ErrorProvider控件,将弹出提示的逻辑替换为:

errorProvider1.SetError(currentTextBox, "输入值已存在,请重新输入!");

无重复时清空提示即可:

errorProvider1.SetError(currentTextBox, string.Empty);

内容的提问来源于stack exchange,提问作者Codeyourbrain98

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 17:15:09