DGV Error When Editing Cell in Last Row of Sorted DGV with Enter Key

Posted on 2010-11-17
Medium Priority
Last Modified: 2012-06-27
I’m getting the following error when I edit a cell in the last row of a sorted dgv and press the Enter key:

“Unable to cast object of type 'System.Windows.Forms.DataGridViewTextBoxCell' to type 'System.Windows.Forms.IDataGridViewEditingCell'”.

I don’t get the error when I press Enter after editing any cell not in the last row, nor when I press Tab after editing any cell in any row (including the last row).

I also don’t get the error if I do not sort the dgv.

Below is the code I use to bind the table to the dgv, format the dgv, and validate the entry.


    Dim ds_Dataset As New DataSet("SE_Dataset")
    Dim dt_Names As DataTable = ds_Dataset.Tables.Add(Me.Name)
    Dim da_Names As OleDbDataAdapter = New OleDbDataAdapter
    Dim bs_Names As New BindingSource


    Private Sub Table_Bind()

        Dim str_SQL As String = "SELECT * " & _
                                "FROM tbl_SE_DS_Path_Names"
        cmd = New OleDb.OleDbCommand(str_SQL, con_SE_MDB)
        da_Names = New OleDbDataAdapter(cmd)
        Dim commandBuilder As New OleDbCommandBuilder(da_Names)
        bs_Names.DataSource = dt_Names
        bs_Names.Sort = "Path_Name"

    End Sub


    Private Sub Table_Format()

        With dgv

            .DataSource = bs_Names

            .AutoGenerateColumns = True
            .AllowUserToAddRows = False
            .AllowUserToDeleteRows = False
            .AllowUserToOrderColumns = False

            .EnableHeadersVisualStyles = False
            .MultiSelect = False
            .SelectionMode = DataGridViewSelectionMode.RowHeaderSelect
            .Sort(.Columns("Path_Name"), _
            .EditMode = DataGridViewEditMode.EditOnKeystrokeOrF2

        End With


Private Sub dgv_CellValidating(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles dgv.CellValidating

    If dgv.IsCurrentCellDirty Then
        If Not Validate_Path_Name(e.FormattedValue) Then
            e.Cancel = True
            da_Names.Update(CType(bs_Names.DataSource, DataTable))
        End If

    End Sub


If I remove the following lines in dgv_CellValidating, the error does not occur:

            da_Names.Update(CType(bs_Names.DataSource, DataTable))

But, by removing these lines, the new cell data isn’t updated in the table.

If I don’t sort the dgv, the error does not occur.

I’ve found a number of posts where folks are experiencing similar problems, but I have not been able to find an answer.

This same question was raised on this forum by Jess31 on 10/8/09.  CodeCruiser provided a link to a ‘similar problem’ that Jess31 indicated had fixed his problem:


I looked at the link and can’t for the life of me figure out where the solution is buried in the link.  La Anh Tu indicated he had a similar problem and his ‘solution’ was adding the following in the CellValidating event:

    e.Cancel = true

La Anh Tu states that ‘currentCell is a cell that is in editing mode.’  I’m not sure what to do with this information.

A few days later, WineNCheese (the original poster of the question on the link) added a comment saying “I was calling Sort in the CellValidating event handler.”

QUESTION:  How can I use a sorted dgv and not get the error when editing a cell in the last row of a dgv with the Enter key?

Thank you in advance for your help!
Question by:CIW_George
  • 4
  • 4
LVL 83

Expert Comment

ID: 34158724
You are still commiting before validating!

What happens if you enclose it in try catch block? Is there any impact on actual functionality?

Author Comment

ID: 34159792
Apparently the CommitEdit and FormattedValue factors are somewhat independent of one another.  Without further changes in my code after your recommendation to use FormattedValue in my previous question, I did not try deleting or moving the CommitEdit line.  For no particular reason, I thought I needed to Commit before getting the FormattedValue.  I now understand they are independent and why.

I moved the CommitEdit line into the Try/Catch block (just before bs_Names.EndEdit) and I still get the error message as previously described.

I believe the error is generated after the dgv is re-sorted after a cell is edited.  If I don’t sort the dgv, then I don’t have any problems.

Here’s my little test.  I have 3 rows in the dgv with a column containing the values ‘a’, ‘m’, and ‘z’ (‘z’ is in the last row).  If I change ‘z’ to ‘x’ with the Enter key, no error is generated.  If I change ‘x’ to ‘k’ with the Enter key, the error is generated.

The only time an error is generated is when a change is made to a cell in the last row of the dgv with the Enter key AND THE ORDER OF ROWS IN THE DGV IS CHANGED AS A RESULT OF SORTING.

In my example, if I changed ‘m’ to ‘r’, no error is generated.  Although ‘m’ is in the last row after the previous changes, the order of rows in the dgv is not changed as a result of sorting.

Interesting, uh?
LVL 83

Assisted Solution

CodeCruiser earned 2000 total points
ID: 34159813
Yeah. But the sorting should be applied AFTER the value has been validated and commited to the data source. The sorting should not be performed before validation. Does the validating event fire when you press enter?
Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.


Author Comment

ID: 34159891
CellValidating fires every time I use the Tab or Enter key to 'complete' a cell editing operation.

Do I have control over when the sorting is applied?  In Table_Format, I setup the sorting, but I don't (intentionally) disable or enable sorting anywhere else.

Should I be doing the EndEdit and Update somewhere else, rather than in the CellValidating routine?  In other words, should CellValidating just set a True/False flag that would be processed in a different routine?
LVL 83

Accepted Solution

CodeCruiser earned 2000 total points
ID: 34159956
Yes try commenting out all the code except true false part.

Author Comment

ID: 34160004
I moved the entire Try/Catch/End block to CellEndEdit and simply set a flag (bol_Validation_Result) to true/false in CellValidating.  CellEndEdit tests bol_Validation_Result and, if true, processes the Try/Catch/End block.

"Look mom, no errors!"

Can you think of any reason why this might not be a viable solution?

Thanks CodeCruiser - you've provided 2 solid solutions in one day!  Ok, maybe this one was a joint effort, but nevertheless, your contribution was invaluable.

I'll try not to press my luck with another question today....

Thank you!

Author Closing Comment

ID: 34160033
CodeCruiser provided the direction and I provided the implementation.
LVL 83

Expert Comment

ID: 34162407
Glad your problem is sorted :-)

Featured Post

Free Backup Tool for VMware and Hyper-V

Restore full virtual machine or individual guest files from 19 common file systems directly from the backup file. Schedule VM backups with PowerShell scripts. Set desired time, lean back and let the script to notify you via email upon completion.  

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A theme is a collection of property settings that allow you to define the look of pages and controls, and then apply the look consistently across pages in an application. Themes can be made up of a set of elements: skins, style sheets, images, and o…
Whether you've completed a degree in computer sciences or you're a self-taught programmer, writing your first lines of code in the real world is always a challenge. Here are some of the most common pitfalls for new programmers.
This Micro Tutorial will teach you how to add a cinematic look to any film or video out there. There are very few simple steps that you will follow to do so. This will be demonstrated using Adobe Premiere Pro CS6.
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question