Solved

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

Posted on 2010-11-17
8
1,350 Views
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)
        da_Names.Fill(dt_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"), _
                  System.ComponentModel.ListSortDirection.Ascending)
            .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
        dgv.CommitEdit(DataGridViewDataErrorContexts.Commit)
        If Not Validate_Path_Name(e.FormattedValue) Then
            e.Cancel = True
        Else
            bs_Names.EndEdit()
            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:

            bs_Names.EndEdit()
            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:

http://social.msdn.microsoft.com/forums/en-US/winforms/thread/387d3934-0197-4dba-95b1-1079ea760df7/

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:

    currentCell.CommitEdit(DataGridViewDataErrorContexts.Commit)
    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!
0
Comment
Question by:CIW_George
  • 4
  • 4
8 Comments
 
LVL 83

Expert Comment

by:CodeCruiser
Comment Utility
You are still commiting before validating!

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

Author Comment

by:CIW_George
Comment Utility
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?
0
 
LVL 83

Assisted Solution

by:CodeCruiser
CodeCruiser earned 500 total points
Comment Utility
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?
0
 

Author Comment

by:CIW_George
Comment Utility
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?
0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
LVL 83

Accepted Solution

by:
CodeCruiser earned 500 total points
Comment Utility
Yes try commenting out all the code except true false part.
0
 

Author Comment

by:CIW_George
Comment Utility
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!
0
 

Author Closing Comment

by:CIW_George
Comment Utility
CodeCruiser provided the direction and I provided the implementation.
0
 
LVL 83

Expert Comment

by:CodeCruiser
Comment Utility
Glad your problem is sorted :-)
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

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…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
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 demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

772 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now