小编Phi*_*ole的帖子

防止 Windows 窗体 DataGridView 在按 ENTER 键时移动到下一行

我知道这个问题(或其变体)已经出现过几次了。但到目前为止我还没有找到适合我的解决方案。

我正在使用 C# 编写一个 Windows 窗体用户控件,其中包含一个 DataGridView,以将员工数据的只读集合呈现为一种美化的选择列表。网格是只读的(在 control_load 上填充)并且将 FullRowSelect 设置为选择方法。我希望用户能够双击鼠标或使用当前行上的 Enter 键来选择该行中的 Id 值,订阅者会选择该值以在其他地方进行处理。

在分配我选择的员工值后处理 KeyDown 事件时,我尝试阻止选择移动到下一行。除非CurrentCell.RowIndex 为零,否则这工作正常。有谁知道我如何才能使其适用于 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 = …
Run Code Online (Sandbox Code Playgroud)

c# user-controls datagridview winforms

1
推荐指数
1
解决办法
8277
查看次数

标签 统计

c# ×1

datagridview ×1

user-controls ×1

winforms ×1