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

Posted on 2010-11-17
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
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 500 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?
Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now


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 500 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

How our DevOps Teams Maximize Uptime

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us. Read the use case whitepaper.

Question has a verified solution.

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

For a while now I'v been searching for a circular progress control, much like the one you get when first starting your Silverlight application. I found a couple that were written in WPF and there were a few written in Silverlight, but all appeared o…
For most people, the WrapPanel seems like a magic when they switch from WinForms to WPF. Most of us will think that the code that is used to write a control like that would be difficult. However, most of the work is done by the WPF engine, and the W…
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.…
Finding and deleting duplicate (picture) files can be a time consuming task. My wife and I, our three kids and their families all share one dilemma: Managing our pictures. Between desktops, laptops, phones, tablets, and cameras; over the last decade…

730 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