DataGridView"Enter"键事件处理

MSa*_*ika 7 .net c# datagridview winforms c#-4.0

我有一个填充了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];
Run Code Online (Sandbox Code Playgroud)

然后,

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());
}
Run Code Online (Sandbox Code Playgroud)

小智 5

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

这是发生的事情:

  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());
    }     
}
Run Code Online (Sandbox Code Playgroud)

我希望这有助于指出你正确的方向.不知道你希望在这里做什么,但希望这能解释你所看到的情况.


小智 5

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

  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;
         }
     }
    
    Run Code Online (Sandbox Code Playgroud)