要使按下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();

相关文章:

  • 2021-06-07
  • 2021-10-12
  • 2022-12-23
  • 2021-11-16
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-10-18
  • 2021-06-03
  • 2021-11-09
  • 2022-12-23
  • 2021-08-22
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案