2

I am facing a problem in datagridview. I have done some code in keydown event for changing the tab focus but when tab reaches last of column it gives a error

"Current cell cannot be set to an invisible cell".

I have made last of cell is invisible because i don't want to be visible that cell.

I have written following code in KeyDown event

private void m3dgvDepositDetails_KeyDown(object sender, KeyEventArgs e)
{
  try
  {
    if (e.KeyCode == Keys.Tab && notlastColumn)
    {
      e.SuppressKeyPress = true;
      int iColumn = m3dgvDepositDetails.CurrentCell.ColumnIndex;
      int iRow = m3dgvDepositDetails.CurrentCell.RowIndex;
      if (iColumn == m3dgvDepositDetails.Columns.Count - 1)
        m3dgvDepositDetails.CurrentCell = m3dgvDepositDetails[0, iRow + 1];
      else
        m3dgvDepositDetails.CurrentCell = m3dgvDepositDetails[iColumn + 1, iRow];
    }
  }
  catch (Exception ex)
  {
    CusException cex = new CusException(ex);
    cex.Show(MessageBoxIcon.Error);
  }
}
LarsTech
  • 80,625
  • 14
  • 153
  • 225
Amit Kumar
  • 1,059
  • 3
  • 22
  • 43

2 Answers2

4

The error is quite self-explanatory: you are setting the CurrentCell as an invisible cell and it is prohibited, that means that the cell's row or the cell's column is hidden. To avoid this don't hide rows/columns or check the Visible property before setting the CurrentCell.

If the problem is the last column you should use:

private void m3dgvDepositDetails_KeyDown(object sender, KeyEventArgs e)
    {
        try
        {
            if (e.KeyCode == Keys.Tab && notlastColumn)
            {
                e.SuppressKeyPress = true;
                int iColumn = m3dgvDepositDetails.CurrentCell.ColumnIndex;
                int iRow = m3dgvDepositDetails.CurrentCell.RowIndex;
                if (iColumn >= m3dgvDepositDetails.Columns.Count - 2)
                    m3dgvDepositDetails.CurrentCell = m3dgvDepositDetails[0, iRow + 1];
                else
                    m3dgvDepositDetails.CurrentCell = m3dgvDepositDetails[iColumn + 1, iRow];

            }
        }
        catch (Exception ex)
        {
            CusException cex = new CusException(ex);
            cex.Show(MessageBoxIcon.Error);
        }
    }
Tobia Zambon
  • 7,479
  • 3
  • 37
  • 69
2

This error occurs when you try to select an hidden cell. Also you should not set rows to invisible in a datagridview since it has bugs.

One solution would be instead of setting the row invisible, just filter the data source and get only those records which you want. This will be slow but can be served as a workaround.

OR

You can try using following (Not tested)

cm.SuspendBinding();
dataGridView1.Rows[0].Visible = false; // Set your datatgridview invisible here
cm.ResumeBinding();
Microsoft DN
  • 9,706
  • 10
  • 51
  • 71