You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WinForm通过TextBox上下方向键移动DataGridView选中项,解决报错及优化代码

TextBox+DataGridView搜索建议功能问题修复方案

原功能说明

配合TextBox与DataGridView实现搜索建议:TextBox输入内容时自动显示原本隐藏的DataGridView,返回匹配的建议项。

现存问题

  • 按下上下方向键时程序抛出System.NullReferenceException异常,错误信息为System.Windows.Forms.DataGridView.CurrentCell.get returned null,在DataGridView无记录时必现
  • KeyDown事件中重复声明功能相同的行、列索引变量,代码冗余

优化后完整代码

private void txtUserTypes_KeyDown(object sender, KeyEventArgs e)
{
    // 前置校验:DataGridView不可见/无数据/无选中单元格时直接跳过,避免空引用异常
    if (!dgvUserTypes.Visible || dgvUserTypes.Rows.Count == 0 || dgvUserTypes.CurrentCell == null)
    {
        return;
    }

    int offset = 0;
    switch (e.KeyCode)
    {
        case Keys.Up:
            offset = -1;
            break;
        case Keys.Down:
            offset = 1;
            break;
        default:
            // 非上下方向键不处理
            return;
    }

    // 统一处理行切换逻辑,变量复用
    int currentRow = dgvUserTypes.CurrentCell.RowIndex;
    int currentCol = dgvUserTypes.CurrentCell.ColumnIndex;
    int targetRow = currentRow + offset;

    // 校验目标行是否在合法范围内
    if (targetRow >= 0 && targetRow < dgvUserTypes.Rows.Count)
    {
        dgvUserTypes.CurrentCell = dgvUserTypes.Rows[targetRow].Cells[currentCol];
    }
    e.Handled = true;
}

private void txtUserTypes_TextChanged(object sender, EventArgs e)
{
    try
    {
        if (txtUserTypes.Text.Length > 0)
        {
            dgvUserTypes.Visible = true;
            ViewSearch(txtUserTypes.Text);
            // 可选优化:搜索结果非空时默认选中第一行,避免CurrentCell为null
            if (dgvUserTypes.Rows.Count > 0)
            {
                dgvUserTypes.CurrentCell = dgvUserTypes.Rows[0].Cells[0];
            }
        }
        else
        {
            dgvUserTypes.Visible = false;
        }
    }
    catch
    {
        // 建议补充异常日志记录,方便后续排查问题
    }
}

修复说明

  • 前置空校验:处理方向键逻辑前先判断DataGridView可见性、行数量、CurrentCell是否为空,不符合条件直接跳过逻辑,彻底解决空引用崩溃问题
  • 逻辑复用:将上下方向键的行切换逻辑统一,仅用偏移量区分不同按键操作,删除重复变量声明,代码更精简易维护
  • 可选增强:在TextChanged搜索完成后如果有结果默认选中第一行,避免首次按方向键时无选中单元格的情况

内容的提问来源于stack exchange,提问作者Ankit Goel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 03:15:04