[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now


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
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 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?
Fill in the form and get your FREE NFR key NOW!

Veeam® is happy to provide a FREE NFR server license to certified engineers, trainers, and bloggers.  It allows for the non‑production use of Veeam Agent for Microsoft Windows. This license is valid for five workstations and two servers.


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

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

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

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Parsing a CSV file is a task that we are confronted with regularly, and although there are a vast number of means to do this, as a newbie, the field can be confusing and the tools can seem complex. A simple solution to parsing a customized CSV fi…
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…
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…

656 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