DataGridView單元格處於編輯狀態觸發KeyDown等事件

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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章