2014-02-19 38 views
4

我有一个DataGridView填充DataTable,有10列。当我单击Enter键时从一行移动到另一行时,我有一个场景,那么我需要选择该行并需要具有该行值。DataGridView“输入”键事件处理

但在这里,当我选择ň个排那么它会自动移动到N + 1行。

请帮我在这...

在页面加载事件:

SqlConnection con = 
    new SqlConnection("Data Source=.;Initial Catalog=MHS;User ID=mhs_mt;[email protected]"); 

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()); 
} 
+0

做你想按回车键然后选择移动到下一排啊? – Sathish

+0

不,我想当前行本身 – MSanika

回答

3

这是在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()); 
    }  
} 

我希望帮助你指出正确的方向。不知道你希望在这里做什么,但希望这可以解释你所看到的事情。

+0

我错了,因为我预期,CurrentRow索引自动增加1,但不是这与GridView的最后一行相同。任何帮助? – MSanika

+0

如果连接PreviewKeyDown事件,它将在DataGridView将单元向下移动一行之前触发。例如,我用我的建议运行你的代码,并得到两个消息框。其中一个表示“2” - 因为它在第三行,而下一个 - 来自KeyPress事件的表示“3” - 在处理程序被调用之前,它向下移动到下一行。 这不是你所遇到的吗? –

+0

我应该提到,如果您正在编辑单元格,按Enter键时不会触发PreviewKeyDown事件,但KeyPress事件也不会发生。这是因为用于编辑DataGridView中的数据的文本框处理键盘输入。你也可以附加一个处理程序,但是这有点多。让我知道你是否希望我告诉你如何。 –

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); 
    } 
} 
+0

谢谢,我一直在寻找这个。 ProcessDialogKey是如何捕获KeyDown的方式,如果我在单元格中 – rosta