DataGridView“Enter”键事件处理

时间:2014-02-19 07:02:57

标签: c# .net winforms c#-4.0 datagridview

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

但是当我选择 n -th行时,它会自动移动到 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());
}

3 个答案:

答案 0 :(得分:5)

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

以下是发生的事情:

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

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

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

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

答案 1 :(得分:2)

使用以下代码添加一个类并修改您的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);
  }
}

答案 2 :(得分:0)

以下解决方案更简单,也可以使用:

  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;
         }
     }
    
相关问题