问题描述
我知道这个问题(或它的变体)已经出现过几次了.但到目前为止,我还没有找到适合我的解决方案.
I know this question (or variants of it) has come up a few times. But So far I have not found a solution that works for me.
我正在使用包含 DataGridView 的 C# 编写 Windows 窗体 UserControl,以将员工数据的只读集合呈现为一种美化的选择列表.网格是只读的(在 control_load 上填充)并且将 FullRowSelect 设置为选择方法.我希望用户能够双击鼠标或使用当前行上的 Enter 键来选择该行的 Id 值,该行由订阅者选取以在其他地方处理.
I'm writing a Windows Forms UserControl using C# containing a DataGridView to present a read-only collection of employee data as a kind of glorified select list. The grid is read-only (populated on control_load) and has FullRowSelect set as the selection method. I want the user to be able either double mouse click or use the Enter Key on the current row to select an Id value form that row which gets picked up by subscribers to handle elsewhere.
在分配我选择的员工值后处理 KeyDown 事件时,我试图阻止选择移动到下一行.这工作正常除非 CurrentCell.RowIndex 为零.有谁知道我如何让它为 CurrentCell.Rowindex = 0 工作?
In handling the KeyDown event after assigning my selected employee value, I attempt to prevent selection moving to the next row. This works fine except when the CurrentCell.RowIndex is zero.Does anyone know how I can get this working for CurrentCell.Rowindex = 0 ?
private void dgvEmployees_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if (dgvEmployees.CurrentRow.Cells[0].Value != null)
{
this.SelectedEmployeeId = (int) dgvEmployees.CurrentRow.Cells[0].Value;
this.OnEmployeeSelected(new TestEmployeeGridListEventArgs() {
SelectedEmployeeId = this.SelectedEmployeeId,
SelectedEmployeeIdentifier = dgvEmployees.CurrentRow.Cells["Identifier"].Value.ToString()
});
}
// Prevent pressing <enter key> moving onto the next row.
if (dgvEmployees.CurrentCell.RowIndex > 0)
{
dgvEmployees.CurrentCell = dgvEmployees[1, dgvEmployees.CurrentCell.RowIndex - 1];
dgvEmployees.CurrentRow.Selected = true;
}
else
{
dgvEmployees.CurrentCell = dgvEmployees[1, 0];
dgvEmployees.Rows[0].Cells[1].Selected = true;
}
}
}
推荐答案
感谢 Reniuz 的提醒.我所需要的只是设置 e.Handled = true
或 e.SuppressKeyPress = true
替换 if (dgvEmployees.CurrentCell.RowIndex > 0)代码> 语句的全部内容.
Thanks to Reniuz fo the heads up. All I needed was either to set e.Handled = true
or e.SuppressKeyPress = true
replacing the if (dgvEmployees.CurrentCell.RowIndex > 0)
statement in it's entirety.
if (e.KeyCode == Keys.Enter)
{
if (dgvEmployees.CurrentRow.Cells[0].Value != null)
{
this.SelectedEmployeeId = (int) dgvEmployees.CurrentRow.Cells[0].Value;
this.OnEmployeeSelected(new TestEmployeeGridListEventArgs() {
SelectedEmployeeId = this.SelectedEmployeeId,
SelectedEmployeeIdentifier = dgvEmployees.CurrentRow.Cells["Identifier"].Value.ToString()
});
}
e.SuppressKeyPress = true;
}
这篇关于防止 Windows 窗体 DataGridView 在按下 ENTER 键时移动到下一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!