DataGridView“回车"关键事件处理 [英] DataGridView "Enter" key event handling

查看:29
本文介绍了DataGridView“回车"关键事件处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a DataGridView populated with DataTable, have 10 columns. I have a scenario when moving from one row to another when I click on Enter key then I need that row should be selected and need to have that row values.

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

But here when I select n-th row then it automatically moves to n+1 Row.

请帮助我...

在页面加载事件中:

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 的默认行为,也是 3rd 方供应商在其他数据网格中的标准行为.

That's the default behaviour of the DataGridView, and pretty standard in other data grids by 3rd party vendors too.

这是发生了什么:

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

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

So by the time the enter key is pressed, the current cell has already changed.

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

You could use the following if you want to get the row that the user was on before the DataGridView changes the row. This should fit in with your existing code (obviously you will need to add the event handler for it):

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

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

I hope that helps point you in the right direction. Not sure what you are hoping to do here, but hopefully this explains what you are seeing happen.

这篇关于DataGridView“回车"关键事件处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆