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

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
  • 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?
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.


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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
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…
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

789 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