在 Keypress 事件中使特定列只接受 datagridview 中的数值 [英] Make a specific column only accept numeric value in datagridview in Keypress event

查看:23
本文介绍了在 Keypress 事件中使特定列只接受 datagridview 中的数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要制作仅在按键事件中仅接受特定列的数值的数据网格视图.有没有最好的方法来做到这一点?

I need to make datagridview that only accept the numeric value for specific column only in keypress event. Is there any best way to do this?

推荐答案

  • 添加EditingControlShowing事件
  • 在 EditingControlShowing 中,检查当前单元格是否位于所需的列中.
  • 在 EditingControlShowing 中注册一个新的 KeyPress 事件(如果上述条件为真).
  • 删除之前在 EditingControlShowing 中添加的任何 KeyPress 事件.
  • 在 KeyPress 事件中,检查如果 key 不是数字,则取消输入.
  • 示例:

    private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        e.Control.KeyPress -= new KeyPressEventHandler(Column1_KeyPress);
        if (dataGridView1.CurrentCell.ColumnIndex == 0) //Desired Column
        {
            TextBox tb = e.Control as TextBox;
            if (tb != null)
            {
                tb.KeyPress += new KeyPressEventHandler(Column1_KeyPress);
            }
        }
    }
    
    private void Column1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
        {
            e.Handled = true;
        }
    }
    

    这篇关于在 Keypress 事件中使特定列只接受 datagridview 中的数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆