ComponentOne True DBGrid Pro 8
Changing cell contents with a single keystroke

The BeforeColEdit event is an extremely versatile way to customize the behavior of True DBGrid editing. BeforeColEdit is fired before any other editing events occur, which gives you the opportunity to do virtually anything you want to before editing begins. For example, you can cancel the edit request and override the built-in text editor with your own drop-down list box.

A True DBGrid control can enter edit mode in one of four ways:

  1. If the user clicks on the current cell with the mouse, editing begins with the current cell contents.

  2. If the user presses the F2 key, editing also begins using the current cell contents.

  3. If the user begins typing, the typed character replaces the contents of the cell and editing begins.

  4. You can set the EditActive property in your code to force editing to begin.

The BeforeColEdit event fires in cases 1, 2, and 3, but not in case 4, since True DBGrid assumes you will never want to cancel a request made from code.

You may want to differentiate a user's edit request based upon whether they used the mouse or the keyboard to start editing. To facilitate this, one of the parameters to BeforeColEdit is KeyAscii, which will be zero if the user clicked on the cell with the mouse, and will be an ASCII character if the user typed a character to begin editing.

When BeforeColEdit is fired, the ASCII character hasn't yet been placed into the current cell, so if you cancel editing in BeforeColEdit, the ASCII key is discarded. This leads to an interesting technique.

Assume you have a Boolean field called Done, and you have set its NumberFormat property to specify Yes/No as the display format. Further assume that, when the user presses Y or N, you want to change the cell contents immediately instead of entering edit mode. Here's how you could accomplish this in BeforeColEdit:

Example Title
Copy Code
Private Sub TDBGrid1_BeforeColEdit(ByVal ColIndex As Integer, _

        ByVal KeyAscii As Integer, Cancel As Integer)

 

    With TDBGrid1.Columns(ColIndex)

        ' If this isn't the "Done" column, or if the user clicked with the mouse,

        ' then simply continue.

        If .DataField <> "Done" Or KeyAscii = 0 Then Exit Sub

 

        ' Cancel normal editing and set the field to the proper result based upon

        ' KeyAscii. Beep if an invalid character was typed.

        Cancel = True

        Select Case UCase$(Chr$(KeyAscii))

            Case "Y"

                .Value = -1

            Case "N"

                .Value = 0

            Case Else

                Beep

        End Select

    End With

End Sub

Note that the event handler terminates when KeyAscii is zero, so mouse editing is still permitted.

 

 


Copyright (c) GrapeCity, inc. All rights reserved.

Product Support Forum  |  Documentation Feedback