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

C# WinForms .NET Framework 表格如何实现一列输文本另一列仅允许输数字

WinForm .NET Framework DataGridView价格列仅允许输入数字实现方案

以下两种方案对应你提到的两种思路,均可实现需求,默认你使用WinForm自带的DataGridView控件作为表格载体:


方案1:输入时实时拦截(推荐,用户无法输入非数字内容)

通过监听EditingControlShowing事件,在价格列进入编辑状态时给输入框绑定按键过滤逻辑,直接拦截非法字符输入:

// 给DataGridView绑定EditingControlShowing事件,可在窗体设计器或者Form_Load中绑定
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    // 仅对价格列做处理,此处假设价格列的索引为1(第二列),可根据你的实际列索引/列名调整
    if (dataGridView1.CurrentCell.ColumnIndex == 1)
    {
        TextBox editBox = e.Control as TextBox;
        if (editBox != null)
        {
            // 先移除旧事件避免重复绑定
            editBox.KeyPress -= PriceEditBox_KeyPress;
            editBox.KeyPress += PriceEditBox_KeyPress;
        }
    }
}

// 按键校验逻辑
private void PriceEditBox_KeyPress(object sender, KeyPressEventArgs e)
{
    // 允许输入的内容:数字、退格键,如需支持小数点可加 && e.KeyChar != '.' 到判断条件中
    if (!char.IsDigit(e.KeyChar) && e.KeyChar != '\b')
    {
        // 拦截非法字符,不会输入到单元格内
        e.Handled = true;
    }
    // 如需限制仅能输入一个小数点,可添加以下逻辑
    // if (e.KeyChar == '.' && (sender as TextBox).Text.Contains("."))
    // {
    //     e.Handled = true;
    // }
}

方案2:失焦时校验

通过监听CellValidating事件,在单元格结束编辑失去焦点时做正则校验,不符合要求则清空内容:

// 给DataGridView绑定CellValidating事件
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    // 仅校验价格列
    if (e.ColumnIndex != 1) return;

    string input = e.FormattedValue?.ToString().Trim() ?? string.Empty;
    // 空值允许逻辑可自行调整,此处示例允许空
    if (string.IsNullOrEmpty(input)) return;

    // 正则校验是否为纯数字,仅支持整数,如需支持小数可修改正则为 @"^\d+(\.\d+)?$"
    if (!System.Text.RegularExpressions.Regex.IsMatch(input, @"^\d+$"))
    {
        // 清空非法值
        dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = string.Empty;
        // 可选:添加报错提示
        // MessageBox.Show("价格列仅允许输入数字");
        // 可选:阻止焦点离开,直到输入合法内容,不需要可删除
        // e.Cancel = true;
    }
}

补充说明

  • 价格列的索引可根据你的实际配置调整,如果你给列设置了Name属性,也可以用dataGridView1.Columns["你的价格列名"].Index来动态获取索引,避免硬编码出错
  • 正则规则可根据业务需求灵活调整,比如支持负数、限定小数位数等

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 05:45:08