由于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;
            }
        }
    }
}


Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐