DataGridView在Cell编辑状态响应回车键下的KeyPress/KeyDown/KeyUp事件


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


如果我们需要做一些事情,比如在DataGridCell中输入值后需要对其验证,如这位朋友遇到的这个问题:
http://social.msdn.microsoft.com/Forums/zh-CN/visualcshartzhchs/thread/2cc22c92-4771-4af4-89cc-c036cd8b556c 他的需求是:

在DataGridView 单元格编辑状态时

按回车时 判断这个单元格的内容是否确定

如果正确光标进入下一行对应的列的单元格中

如果不正确光标还是停留本单元格中


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


建一个类:

namespace WindowsFormsApplication
{
public sealed class MyDataGridView : DataGridView
{

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Enter)
{
this.OnKeyPress(new KeyPressEventArgs('r'));
return true;
}
else
return base.ProcessCmdKey(ref msg, keyData);
}
}
}

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

private void myDataGridView1_KeyPress(object sender, KeyPressEventArgs e)
{

if (e.KeyChar == 'r')
{
DataGridView dgv = sender as DataGridView;
DataGridViewCell cell = dgv.CurrentCell;
if (cell.IsInEditMode)
{
//限制单元格只能输入test 
if (cell.EditedFormattedValue != null && cell.EditedFormattedValue.ToString() != "test")
{
MessageBox.Show("输入内容不合格");
}
else
{
dgv.CurrentCell = dgv[cell.ColumnIndex, cell.RowIndex + 1];
}
}
}
}

当然为了保证用户直接将鼠标移动到新的单元格也能做数据的核对,我们还需要添加对这个控件的CellEndEdit事件的处理:

private void myDataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
DataGridView dgv = sender as DataGridView;
DataGridViewCell cell = dgv[e.ColumnIndex, e.RowIndex];
{
//限制单元格只能输入test 
if (cell.EditedFormattedValue != null && cell.EditedFormattedValue.ToString() != "test")
{
MessageBox.Show("输入内容不合格");

dgv.CurrentCell = cell ;
}
else
{
dgv.CurrentCell = dgv[cell.ColumnIndex, cell.RowIndex + 1];
}
}
}

这样无论是用户按的Enter键还是直接移动鼠标就都会做相应的验证了。
为了使得代码便于维护最好将判断校验代码单独写到一个方法,供这个两个事件处理调用。


转载自:http://hi.baidu.com/topkaze/item/40e83c0c46dc7519acdc701f




  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值