views:

514

answers:

1

Coding in Delphi, attaching an OnKeyPress event handler to a TStringGrid:

The OnKeyPress event fires before the grid cell that the user is typing into has actually updated its value with the key that has been pressed. This is obviously a problem, when I want to know what the contents of that cell are at this moment, as in, as the user modifies it.

The "hacked" solution is simple, if you're not considering every detail: just grab the value from the cell and, since the OnKeyPress event comes along with a Key parameter, append that value to the end - now you have the current value of the cell!

False. What if the user has selected all the text in the cell (ie: "foo") and they are now typing 'b'. Since they selected the text, it will be erased and replaced with the letter 'b'. However, the value of the cell will still display as "foo" in OnKeyPress, and the value of Key will be 'b', so the above logic would lead the application to conclude that the cell now contains "foob", which we know is not true.

So. Does anybody know how to get around this problem? Is there a way to make OnKeyPress react after the grid's contents have been updated, or perhaps a way to force an update at the start of the handler? I am desperately avoiding the use of the OnKeyUp event here, so any suggestions aside from that would be greatly appreciated.

+3  A: 

If you wish to respond to a change in a cells value why are you not using the OnSetEditText event ?

Keyboard events are for responding to keyboard input, not a controls response to that input. A control will typically provide one or more additional events to allow an application to respond to the controls response to some input - in this case, where a keyboard input results in a cell value being modified, rather than a change in cell selection, for example.

As an aside, it is quite natural that these events should be occuring prior to the grid controls response to those events, so that you may effectively "filter" such events before they reach the control, e.g. to prevent a particular keyboard input from affecting the value of a cell.

Deltics
Technically **OnSetEditText** seems to fire whenever the cell loses focus - whether or not the value has actually changed. Nonetheless, if I compare values to see if it has actually changed, this should perform wonderfully for me. Thanks a lot.
JMTyler