[英]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 方供应商在其他数据网格中的标准行为。
这是发生的事情:
所以当按下回车键时,当前单元格已经改变了。
如果您想在 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);
}
}
以下解决方案更简单并且也有效:
在 .Designer.cs 文件中:
this.dataGridView1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.dataGridView1_KeyDown);
在文件背后的代码中:
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.