c#DataGridView响应键盘事件
DataGridView中列的事件,这种事件放在DataGridView中,象我修改的程序是要求在单元格里加上F4单机快捷事件,但DataGridView中只提供本身的KeyDown事件,实现不了,如果用下列方法就能实现啦!
首先,要先定义一个Class级的变量(放在Form内,可别放在外面),
private DataGridViewTextBoxEditingControl EditingControl;
其次,添加EditingControlShowing事件委托
this.dgvDetails.EditingControlShowing += new System.Windows.Forms.DataGridViewEditingControlShowingEventHandler(this.dgvDetails_EditingControlShowing);
第三步,定义委托的方法:
private void dgvDetails_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
EditingControl = (DataGridViewTextBoxEditingControl)e.Control;
EditingControl.KeyPress -= new KeyPressEventHandler(EditingControl_KeyPress);//经ijunxiong测试这里+=会有问题,叠加事件,可以-=,不会出错
EditingControl.KeyPress += new KeyPressEventHandler(EditingControl_KeyPress);
}
注:加粗的地方很重要,主要是针对列的事件,这是关键.
第四步,定义列的委托方法啦,引用以其他控件引用完全相同.
private void EditingControl_KeyPress(object sender, KeyPressEventArgs e)
{
//省略-----------------------
}