Solved

Why doesn't this code work?

Posted on 2015-01-15
9
82 Views
Last Modified: 2015-01-15
I know the above question is very broad and open-ended, however, the code isn't that much. My scenario is that I have a Windows Form that contains a DataGridView (dgv). This grid is setup to accept numeric values only. The code in question is to prevent any empty cells in columns 1 & 2 which are the only editable cells in the grid. Columns 0 & 3 are ReadOnly. I have attached a screenshot to show where I am in the process.

DEFINED EVENTS:
txtTensionEdit_KeyDown
dgvTension_EditingControlShowing
dgvTension_CellValidating

======================================================

Initially, when I enter the cell, I press the delete key to clear out the cell. Then I press a direction key to test the "dgvTension_CellValidating" Event making sure the message "Cell cannot be empty!" is displayed. That works fine!

Now the problem!

I've entered numeric values in the red highlighted cell. Each time I enter a numeric value, the "txtTensionEdit_KeyDown" event fires and it passes the edits. As soon as I hit a direction key, the "dgvTension_CellValidating" fires and it still displays the message "Cell cannot be empty!" even though there clearly is data in the cell.

What am I missing here?


    Private Sub dgvTension_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles dgvTension.EditingControlShowing
        Try
            Dim txtTensionEdit As TextBox = CType(e.Control, TextBox)

            EH.ErrorMessage = String.Empty

            RemoveHandler txtTensionEdit.KeyDown, AddressOf txtTensionEdit_KeyDown
            AddHandler txtTensionEdit.KeyDown, AddressOf txtTensionEdit_KeyDown
            AddHandler txtTensionEdit.KeyPress, AddressOf txtTensionEdit_KeyPress

        Catch ex As Exception
            EH.ErrorMessage = "frmCalibration_3/dgvTension_EditingControlShowing() - " & ex.Message & "...Contact Engineering!" & "~E"
        End Try

        EH.ProcessMessages(Me, sbr, EH.ErrorMessage)
    End Sub
   '
   '
   '
    Private Sub txtTensionEdit_KeyDown(sender As Object, e As KeyEventArgs)
        Try
            EH.ErrorMessage = String.Empty

            iTensionColIDX = dgvTension.CurrentCell.ColumnIndex
            iTensionRowIDX = dgvTension.CurrentCell.RowIndex

            If iTensionRowIDX = dgvTension.RowCount - 1 Then
                blnLastRow = True
            End If

            If e.Handled = True Then
                Exit Sub
            ElseIf cboManual.Checked Then
                If e.KeyCode = Keys.Return Then
                    If iTensionRowIDX = dgvTension.RowCount - 1 Then
                        dgvTension.EndEdit()
                        dgvTension.Refresh()

                        ProcessTensionTestLoadResults(dgvTension)
                    End If
                End If
            ElseIf e.KeyCode < Keys.D0 OrElse e.KeyCode > Keys.D9 Then
                If e.KeyCode < Keys.NumPad0 OrElse e.KeyCode > Keys.NumPad9 Then
                    If e.KeyCode <> Keys.Back And e.KeyCode <> Keys.Enter And e.KeyCode <> Keys.Decimal And e.KeyCode <> Keys.Delete Then
                        blnNonNumberedEntered = True
                    End If
                End If
            End If

            If Control.ModifierKeys = Keys.Shift Then
                blnNonNumberedEntered = True
            End If

        Catch ex As Exception
            EH.ErrorMessage = "frmCalibration_3/txtTensionEdit_KeyDown() - " & ex.Message & "...Contact Engineering!" & "~E"
        End Try

        EH.ProcessMessages(Me, sbr, EH.ErrorMessage)
    End Sub
   '
   '
   '
    Private Sub dgvTension_CellValidating(sender As Object, e As DataGridViewCellValidatingEventArgs) Handles dgvTension.CellValidating
        Try
            Dim cl As DataGridViewCell = dgvTension.CurrentCell

            EH.ErrorMessage = String.Empty
            gblnEmptyCell = False

            Select Case e.RowIndex
                Case 0
                    Select Case e.ColumnIndex
                        Case 2  'Output Cell (0 Load)
                            If cl.Value = String.Empty Then
                                gblnEmptyCell = True
                                EH.ErrorMessage = "Cell cannot be empty!" & "~I"
                            End If
                    End Select
                Case Else
                    Select Case e.ColumnIndex
                        Case 1  'Output Cell 
                            If cl.Value = String.Empty Then
                                gblnEmptyCell = True
                                EH.ErrorMessage = "Cell cannot be empty!" & "~I"
                            End If
                        Case 2

                    End Select
            End Select

        Catch ex As Exception
            EH.ErrorMessage = "frmCalibration_3/dgvTension_CellValidating() - " & ex.Message & "...Contact Engineering!" & "~E"
        End Try

        EH.ProcessMessages(Me, sbr, EH.ErrorMessage)

        If gblnEmptyCell Then
            e.Cancel = True
        End If
    End Sub

Open in new window

0
Comment
Question by:BlakeMcKenna
  • 3
  • 3
  • 2
  • +1
9 Comments
 
LVL 24

Expert Comment

by:Phillip Burton
Comment Utility
It would be helpful if you could add breakpoints and go through the code and let us know where execution is stopping.
0
 

Author Comment

by:BlakeMcKenna
Comment Utility
I've attached a screenshot of stepping through the code. At this point, I've hit a direction key.
SteppingThroughCode.jpg
0
 

Author Comment

by:BlakeMcKenna
Comment Utility
    Dim cl As DataGridViewCell = dgvTension.CurrentCell

Open in new window


My biggest question and probably most obvious is using the above statement, there should be data in the cell at this point "111"....and yet going through the code it shows that it's value is "".
0
 
LVL 40

Expert Comment

by:Jacques Bourgeois (James Burger)
Comment Utility
The CurrentCell is in limbo in many events. Instead of working with the CurrentCell in most event, work with the data provided through the e parameter to reference the cell:

Dim cl As DataGridViewCell = dgvTension.Item(e.ColumnIndex, e.RowIndex)

Open in new window

0
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

 
LVL 85

Accepted Solution

by:
Mike Tomlinson earned 500 total points
Comment Utility
Better yet, the value is already provided to you via "e.FormattedValue":
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellvalidating(v=vs.110).aspx

Example from MSDN:
Private Sub dataGridView1_CellValidating(ByVal sender As Object, _
    ByVal e _
    As DataGridViewCellValidatingEventArgs) _
    Handles dataGridView1.CellValidating

    Me.dataGridView1.Rows(e.RowIndex).ErrorText = "" 
    Dim newInteger As Integer 

    ' Don't try to validate the 'new row' until finished  
    ' editing since there 
    ' is not any point in validating its initial value. 
    If dataGridView1.Rows(e.RowIndex).IsNewRow Then Return 
    If Not Integer.TryParse(e.FormattedValue.ToString(), newInteger) _
        OrElse newInteger < 0 Then

        e.Cancel = True 
        Me.dataGridView1.Rows(e.RowIndex).ErrorText = "the value must be a non-negative integer" 

    End If 
End Sub

Open in new window

0
 
LVL 85

Expert Comment

by:Mike Tomlinson
Comment Utility
James, the value hasn't been "committed" to the cell yet, so retrieving it from Item() will still show it as blank (or whatever value it was before editing).
0
 
LVL 40

Expert Comment

by:Jacques Bourgeois (James Burger)
Comment Utility
Ooop. You're right Mike. I simply reacted to the CurrentCell and did not see that it was in Validating. This is what happens when you cannot make your usual coffee in the morning (diesel in the water in my home town today).

You are right with e.FormattedValue.
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
Comment Utility
Oh no!  No coffee?  I would be a very sad fellow...   =\
0
 

Author Closing Comment

by:BlakeMcKenna
Comment Utility
Thanks Mike...that worked!
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

Introduction As chip makers focus on adding processor cores over increasing clock speed, developers need to utilize the features of modern CPUs.  One of the ways we can do this is by implementing parallel algorithms in our software.   One recent…
Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
This video discusses moving either the default database or any database to a new volume.
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…

743 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

8 Experts available now in Live!

Get 1:1 Help Now