Home > Enterprise >  moving through datagridview with textbox keys up and keys down
moving through datagridview with textbox keys up and keys down

Time:10-21

I am working on a project where i am using a textbox with a datagridview in which as soon as i type somthing in the textbox the datagridview becomes visible from invisible and starts giving me suggestions according to my keystrokes . the code is written below .

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
        {

        }
    }

The problem is as soon as i press "up" key on my keyboard the program crashes with an exception " System.NullReferenceException: 'Object reference not set to an instance of an object.'

System.Windows.Forms.DataGridView.CurrentCell.get returned null." . I dont want the program to crash instead it should do nothing if there is no record on the datagridview . Also i want to optimise my code in keydown event as i have declared variables twice ( ie rpos and rpos1 ) which are basically doing same thing .

CodePudding user response:

Without a running sample, I would suggest something simple like ...

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;
        }
}
  • Related