FormatException Error Handling Issue

Posted on 2007-08-09
Last Modified: 2011-09-20
Hi all,

I have compiled the following code to hande errors on my winforms datagridview:

    Private Sub DG_platesNEW_CellBeginEdit(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellCancelEventArgs) Handles DG_platesNEW.CellBeginEdit

        cellno = DG_platesNEW.Rows(e.ColumnIndex).Index 'This holds the cellno incase the cell is left by the user.
        mSavedValue = DG_platesNEW.Rows(e.RowIndex).Cells(e.ColumnIndex).Value

    End Sub

    Private Sub DG_platesNEW_DataError(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewDataErrorEventArgs) Handles DG_platesNEW.DataError

        If TypeOf e.Exception Is System.Data.NoNullAllowedException Then
            e.Cancel = True
            MessageBox.Show("Field must have a value!", "Please enter some valid data.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            DG_platesNEW.Rows(e.RowIndex).Cells(cellno).Value = mSavedValue
        ElseIf TypeOf e.Exception Is System.FormatException Then
            e.Cancel = True
            MessageBox.Show("Value not allowed!", "Please enter some valid data.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
          ' DG_platesNEW.Rows(e.RowIndex).Cells(cellno).Value = mSavedValue
        End If

    End Sub

The part I am struggling to figure out is the FormatException error. I am trying to reject changes and re-insert the mSavedValue value back into the cell. However, when I test this, I need to run through the if statement twice for it to replace the value. However, once I have run through the error message twice, I can then use this error trap anywhere on that row and it works fine. Once I move from the row and test it on another row I get the same problem... Run it through the error twice though and again the value is replaced.

Any ideas guys?

Question by:FMabey
    LVL 34

    Accepted Solution

    Have a look at this little demo.  One form, two datagridviews - dgv1 and dgv2 - and this code.

    Public Class Form1

        Private dt As New DataTable("TestTable")

        Private Sub filltable()
            For i As Integer = 0 To 2
                Dim col As New DataColumn("Col" & i.ToString, GetType(Integer))
            For i As Integer = 1 To 5
                Dim row As DataRow = dt.NewRow
                For j As Integer = 0 To 2
                    row(j) = i * j
        End Sub

        Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            dgv1.DataSource = dt
            dgv2.DataSource = dt
        End Sub

        Private Sub dgv1_DataError(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewDataErrorEventArgs) Handles dgv1.DataError
            e.Cancel = True
        End Sub
    End Class

    It is to demonstrate, albeit somewhat superficially, how changes are "committed" so far as bound datagridviews are concerned.  Make a (valid) change in a cell in dgv1 then move to a cell on the same row in that dgv.  You will notice that dgv2 doesn't change.  Now move to a cell on a different row in dgv1.  You will notice that dgv2 does change.  That doesn't actually _prove_ the relevant point, but it exemplifies it.  And it is that changes made in a datagridview are only (automatically) sent on - "committed" - to the (ulitmate) datasource when focus shifts to a different row/record.  So, until that has happened, they can be reversed in the dgv itself: there is no need to save the old value and put it in the datasource or to .RejectChanges on the datasource.

    Now put an invalid entry in a cell in dgv1 and move either to a different cell on the same row, or to a different row in the same dgv, or even to the other dgv.  The movement itself is cancelled by e.Cancel = True and the wrong value will be replaced by the original right one by the .CancelEdit.

    I suppose there may be reasons unconnected with the specific code that you show here why you need to take the steps that your code does show.  But I just wondered whether you were making unnecessary work for yourself rathr than letting the datagridview do its own thing (with just a little help from your code).

    LVL 3

    Author Comment

    Looks like I was making a mountain out of a mole hill! Still, I learnt a few things whilst doing so! Thanks!

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    Introduction When many people think of the WebBrowser ( control, they immediately think of a control which allows the viewing and navigation of web pages. While this is true, it's a…
    1.0 - Introduction Converting Visual Basic 6.0 (VB6) to Visual Basic 2008+ (VB.NET). If ever there was a subject full of murkiness and bad decisions, it is this one!   The first problem seems to be that people considering this task of converting…
    Migrating to Microsoft Office 365 is becoming increasingly popular for organizations both large and small. If you have made the leap to Microsoft’s cloud platform, you know that you will need to create a corporate email signature for your Office 365…
    how to add IIS SMTP to handle application/Scanner relays into office 365.

    759 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

    10 Experts available now in Live!

    Get 1:1 Help Now