DataGridView单元格处于编辑状态触发KeyDown等事件

本文介绍了一种在DataGridView中处理Enter键的方法,通过自定义控件MoMoDataGridView并重写ProcessCmdKey方法,使得按Enter键时可以触发自定义的KeyPress事件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

由于DataGridView的单元格DataGridCell处于编辑的时候,
当你按Enter键,那么DataGridView是不会激发KewPress/KeyDown/KeyUp这些事件的,
因为这个时候的DataGridView是一个容器。


我们无法直接在DataGridView的KeyPress事件中做处理,原因上面已经说明,也无法使用CellEndEdit这个事件,
因为这个事件不一定是通过Enter来触发的,直接鼠标移动到其他单元格也会的,因此我们需要修改一下:

1、项目里,添加组件MoMoDataGridView

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Text;
using System.Windows.Forms;

namespace UFIDA.U8.Portal.Interface
{
    public partial class MoDataGridView : DataGridView
    {
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.F2)
            {
                this.OnKeyPress(new KeyPressEventArgs('f'));
                return true;
            }
            else if (keyData == Keys.Enter)
            {
                this.OnKeyPress(new KeyPressEventArgs('e'));
                return true;
            }
            else if (keyData == Keys.Delete)
            {
                this.OnKeyPress(new KeyPressEventArgs('d'));
                return true;
            }
            else
                return base.ProcessCmdKey(ref msg, keyData);
        }
    }
}

2、然后将这个控件拖到窗体中 添加KeyPress事件

private void dgData_KeyPress(object sender, KeyPressEventArgs e)
{
    dgData.EndEdit();

    int irows = dgData.CurrentCell.RowIndex;
    int icols = dgData.CurrentCell.ColumnIndex;

    if (irows > -1 && icols > -1)
    {
        if (e.KeyChar == 'd')
        {
            if (dgData.CurrentCell.ReadOnly == false)
                dgData.CurrentCell.Value = null;
        }
        if (e.KeyChar == 'f')
        {
            if (dgData.CurrentCell.ColumnIndex == 1)
            {
                string cinv = "";
                if (dgData.CurrentCell.Value != null)
                {
                    if (dgData.CurrentCell.Value.ToString() != "")
                        cinv = dgData.CurrentCell.Value.ToString();
                }

                frmInfor infor = new frmInfor("存货", cinv);
                infor.ShowDialog();
                dgData.CurrentCell.Value = frmInfor.rc;
            }
        }
    }
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值