繁体   English   中英

DataGridView “Enter”键事件处理

[英]DataGridView “Enter” key event handling

我有一个用 DataTable 填充的 DataGridView,有 10 列。 当我单击 Enter 键时从一行移动到另一行时,我需要选择该行并需要具有该行值。

但是在这里,当我选择第n行时,它会自动移动到n+1行。

请帮助我在这...

在页面加载事件中:

SqlConnection con = 
    new SqlConnection("Data Source=.;Initial Catalog=MHS;User ID=mhs_mt;Password=@mhsinc");

DataSet ds = new System.Data.DataSet();
SqlDataAdapter da = new SqlDataAdapter("select * from MT_INVENTORY_COUNT", con);
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];

然后,

private void dataGridView1_KeyPress(object sender, KeyPressEventArgs e)
{
     if (e.KeyChar == (Char)Keys.Enter)
     {
           int i = dataGridView1.CurrentRow.Index;
           MessageBox.Show(i.ToString());
     }     
}

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    int i = dataGridView1.CurrentRow.Index;
    MessageBox.Show(i.ToString());
}

这是 DataGridView 的默认行为,也是第 3 方供应商在其他数据网格中的标准行为。

这是发生的事情:

  1. 用户按下回车键
  2. DataGridView 接收 KeyPress 事件并执行各种操作(例如结束编辑等),然后将单元格向下移动一行。
  3. 然后 DataGridView 会检查您是否连接了任何事件处理程序并触发它们。

所以当按下回车键时,当前单元格已经改变了。

如果您想在 DataGridView 更改行之前获取用户所在的行,您可以使用以下内容。 这应该适合您现有的代码(显然您需要为其添加事件处理程序):

void dataGridView1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        int i = dataGridView1.CurrentRow.Index;
        MessageBox.Show(i.ToString());
    }     
}

我希望这有助于为您指明正确的方向。 不确定您希望在这里做什么,但希望这可以解释您所看到的情况。

使用以下代码添加一个类并修改您的 GridView 设计器页面,即,

this.dataGridView1 = New System.Windows.Forms.DataGridView();

this.dataGridView1 = new GridSample_WinForms.customDataGridView();

类文件是:

class customDataGridView : DataGridView
{
  protected override bool ProcessDialogKey(Keys keyData)
  {
     if (keyData == Keys.Enter)
     {
        int col = this.CurrentCell.ColumnIndex;
        int row = this.CurrentCell.RowIndex;
        this.CurrentCell = this[col, 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;
        this.CurrentCell = this[col, row];
        e.Handled = true;
     }
     base.OnKeyDown(e);
  }
}

以下解决方案更简单并且也有效:

  1. 在 .Designer.cs 文件中:

    this.dataGridView1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.dataGridView1_KeyDown);

  2. 在文件背后的代码中:

     private void dataGridView1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyData == Keys.Enter) { // Handle event e.Handled = true; } }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM