使用向上和向下键的文本框键在 datagridview 中移动

moving through datagridview with textbox keys up and keys down

我正在做一个项目,在该项目中我使用带有 datagridview 的文本框,只要我在文本框中键入内容,datagridview 就会从不可见变为可见,并开始根据我的击键给我建议。代码写在下面。

private void txtUserTypes_KeyDown(object sender, KeyEventArgs e)
    {

        switch (e.KeyCode)
        {
            case Keys.Up:
                int rpos = dgvUserTypes.CurrentCell.RowIndex;
                int cpos = dgvUserTypes.CurrentCell.ColumnIndex;
                rpos--;
                if (rpos >= 0) dgvUserTypes.CurrentCell = dgvUserTypes.Rows[rpos].Cells[cpos];
                e.Handled = true;
                break;
            case Keys.Down:
                int rpos1 = dgvUserTypes.CurrentCell.RowIndex;
                int cpos1 = dgvUserTypes.CurrentCell.ColumnIndex;
                rpos1++;
                if (rpos1 < dgvUserTypes.Rows.Count) dgvUserTypes.CurrentCell = dgvUserTypes.Rows[rpos1].Cells[cpos1];
                e.Handled = true;
                break;
        }
}
   private void txtUserTypes_TextChanged(object sender, EventArgs e)
    {
        try
        {
            if(txtUserTypes.Text.Length >0)
            {
                dgvUserTypes.Visible = true;
                ViewSearch(txtUserTypes.Text);
            }
            else
            {
                dgvUserTypes.Visible = false;
            }
        }
        catch
        {

        }
    }

问题是当我按下键盘上的“向上”键时,程序崩溃并出现异常 " System.NullReferenceException: 'Object reference not set to an instance of an object.'

System.Windows.Forms.DataGridView.CurrentCell.get returned null." 。我不希望程序崩溃,相反,如果 datagridview 上没有记录,它应该什么也不做。 我还想在 keydown 事件中优化我的代码,因为我已经声明了两次变量(即 rpos 和 rpos1),它们基本上做同样的事情。

没有 运行 示例,我会建议一些简单的东西,例如...

private void txtUserTypes_KeyDown(object sender, KeyEventArgs e)
{
        if (dgvUserTypes.CurrentCell == null) return;

        int rpos = dgvUserTypes.CurrentCell.RowIndex;
        int cpos = dgvUserTypes.CurrentCell.ColumnIndex;

        switch (e.KeyCode)
        {
            case Keys.Up:
                rpos--;
                if (rpos >= 0) dgvUserTypes.CurrentCell = dgvUserTypes.Rows[rpos].Cells[cpos];
                e.Handled = true;
                break;

            case Keys.Down:
                rpos++;
                if (rpos < dgvUserTypes.Rows.Count) dgvUserTypes.CurrentCell = dgvUserTypes.Rows[rpos].Cells[cpos];
                e.Handled = true;
                break;
        }
}