C# :DataGridView中使按下Enter键达到与按下Tab键一样的效果

本文引用自:

http://hi.baidu.com/yk%B1%B1%BC%AB%D0%C7/blog/item/d03f73b2b0862aacd8335a79.html

 

要使按下Enter键达到与按下Tab键一样的效果,我们需要从DataGridView中派生出一个类,写一个自定义的DataGridView控件。这里有两个方面需要考虑。一方面,当DataGridView不处于编辑状态:在这种情况下,我们需要重写OnKeyDown事件来实现我们所需要的定位逻辑。另一方面,当DataGridView处于编辑的状态下:在这种情况下,Enter键是在ProcessDialogKey事件中被处理,因此我们需要重写该事件。详见以下示例:

 

class myDataGridView : DataGridView

{

    
protected override bool
ProcessDialogKey(Keys keyData)

     {

        
if (keyData ==
Keys.Enter)

         {

            
int col = this
.CurrentCell.ColumnIndex;

            
int row = this
.CurrentCell.RowIndex;

            
if (row != this
.NewRowIndex)

             {

                
if (col == (this.Columns.Count - 1
))

                 {

                     col
= -1
;

                     row
++
;

                 }

                
this.CurrentCell = this[col + 1
, row];

             }

            
return true
;

         }

        
return base
.ProcessDialogKey(keyData);

     }



    
protected override void
OnKeyDown(KeyEventArgs e)

     {

        
if (e.KeyData ==
Keys.Enter)

         {

            
int col = this
.CurrentCell.ColumnIndex;

            
int row = this
.CurrentCell.RowIndex;

            
if (row != this
.NewRowIndex)

             {

                
if (col == (this.Columns.Count - 1
))

                 {

                     col
= -1
;

                     row
++
;

                 }

                
this.CurrentCell = this[col + 1
, row];

             }

             e.Handled
= true
;

         }

        
base
.OnKeyDown(e);

     }

}

 

运用:

this.dataGridView1 = new myDataGridView();

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值