views:

892

answers:

3

I'm hosting a custom editing control in a DataGridView, which for the record is a TextBox and Button together in a UserControl. I have inherited from DataGridViewColumn for the new column and DataGridViewTextBoxCell for the new cell.

With a normal DataGridViewTextBoxCell, if you press a key when the cell has focus, it will begin edit mode and the character you typed will appear in the TextBoxEditingControl. However, in my inherited cell, no value is being passed down on keypress. (In fact, you have to manually pass the current cell value in InitializeEditingControl or nothing will show up at all.) So, the first character you type (the one that begins edit mode) is lost.

I have tried OnKeyPress, OnKeyDown, and OnKeyUp in the DataGridViewCell but they never get called. KeyEntersEditMode, however, does seem to get called, and only when it is checking against a pressed key, so this might be a good place to start. The problem then becomes how to translate a KeyEventArgs to a char. This is trivial for alphabet and numbers, but since not all keyboards are created equal, handling other keys is messy and complicated at best. If there's a converter class that will do this automagically, please enlighten me.

Has anyone else encountered this problem or found a good workaround?

Note: This problem applies when EditMode is set to any variation of EditOnKeystroke. Setting to EditOnEnter is a valid workaround for my project, but I'd like to emulate the default behavior of the TextBoxEditingControl as well.

A: 

I Have exactly the same problem and I am also searching for a good solution.

Good luck, and let me know what you learn. Maybe two heads can solve this one? The only thing I'd come up with was to use EditOnEnter. Maybe looking at the DataGridViewTextBoxCell in Reflector could prove useful - I haven't tried that yet. Either way, I'm glad I'm not the only one here...
lc
+1  A: 

Try setting the KeyPreview of the user control to true. Then check if the key which starts the editing process fires the keydown even for the user control. If it does, you can simply store and assign the character once the text control enters edit mode.

Bobby Alexander
A: 

My Solution is to override OnKeyPress on the custom UserControl.

protected override void OnKeyPress(KeyPressEventArgs e)
{
  _textBox.Text = e.KeyChar.ToString();
  _textBox.SelectionStart = 1;
  _textBox.SelectionLength = 0;
  base.OnKeyPress(e);
}
sschoenb
Does the UserControl get the keypress passed down to it from the DataGridView?
lc