Getting Unable to cast object of type DataGridViewTextBoxCell' to type DataGridViewEditingCell when the enter key is pressed

Cynolycus 260 Reputation points
2023-04-29T06:23:00.12+00:00

Does anybody know why I would be getting this error when the Enter key is pressed after entering data into a cell in a DGV?

The code automatically saves the data to a table after the required fields have been filled and works fine if you use the Tab key or click on cells, but if you enter data in a cell and then use the Enter key to go to another cell it throws this error and displays the No Symbols Loaded tab and Symbol loading skipped. If you were to click on another cell after entering data in a cell then the Enter key doesn't produce the error.

System.InvalidCastException: 'Unable to cast object of type 'System.Windows.Forms.DataGridViewTextBoxCell' to type 'System.Windows.Forms.IDataGridViewEditingCell'.'

Developer technologies VB
{count} votes

1 answer

Sort by: Most helpful
  1. Cynolycus 260 Reputation points
    2023-04-30T14:47:25.97+00:00

    The cause of the problem was the default behaviour of the Enter key to move to the next row down, which didn't exist.

    I couldn't trap the Enter key with OnKeyPress or any other event so with much looking I found a post with some code that made the Enter key act as a Tab key, but it also prevented other controls from working as they should because they needed the default behaviour of the Enter key. More looking and I found some code for another control and pieced it together with what I already had, to make the code for a Custom Class for the DataGridView. Then I had to find out how to make a Custom DataGridView and get it on my form, I've never done it before. The end result is a small piece of code that works perfectly.

    This is what I ended up with.

    Public Class MyDataGridView
        Inherits Windows.Forms.DataGridView
        Protected Overrides Function ProcessCmdKey(ByRef msg As Message, keyData As Keys) As Boolean
            'Make the Enter key behave as a Tab key
            If msg.WParam.ToInt32() = CInt(Keys.Enter) Then
                SendKeys.Send("{Tab}")
                Return True
            End If
            ' Handle all other keys as usual
            Return MyBase.ProcessCmdKey(msg, keyData)
        End Function
    
    End Class
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.