2

I have a winforms application with a DataGridView that has some multi-line text cells. The default behavior of the DataGridViewTextBoxEditingControl seems strange. For some reason, if a cell is being edited and the selection is at the very end of the text (at the end of the very last word on the last line), if the user presses the down arrow key, it sets the selection back to the start of the text in that cell (without leaving edit mode) instead of taking them to the next cell. If down arrow is pressed while editing any line other than the last line, the insertion point moves to the next line as expected. If down arrow is pressed while editing the last line but not at the very end of the line, then editing ends and the next cell (below) becomes the new current cell. Is there any (good/simple) way to change this behavior? I came up with this solution, but I'm not very happy about having to put in kludgey code to fix what appears to be a bug in the .Net control.

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (msg.WParam.ToInt32() == (int)Keys.Down &&
        IsCurrentCellInEditMode && EditingControl is DataGridViewTextBoxEditingControl &&
        ((DataGridViewTextBoxEditingControl)EditingControl).SelectionStart == EditingControl.Text.Length)
    {
        EndEdit();
        if (CurrentCellAddress.Y < RowCount - 1)
            CurrentCell = this[CurrentCellAddress.X, CurrentCellAddress.Y + 1];
        return true;
    }
    return base.ProcessCmdKey(ref msg, keyData);
}
Tom Bogle
  • 464
  • 4
  • 18
  • There's lots of weird behavior in the datagridview. I've spent 2 years fighting with it, and I have a subclassed version with almost 1000 lines of code in it that makes it do what I want. – Isaac Bolinger Jul 18 '12 at 06:19
  • You might as start your own subclassed version and run with it. You'll likely find a multitude of things about the datagridview that you will want to fix. – Isaac Bolinger Jul 18 '12 at 06:20
  • I haven't yet tried multiline textboxes in the dgv yet, though. – Isaac Bolinger Jul 18 '12 at 06:22
  • We do have a sub-classed version of the DataGridView. I hadn't really considered adding this code there, but maybe that's the thing to do. – Tom Bogle Jul 18 '12 at 14:38
  • Good call! Turns out the problem is actually a bug in our sub-class, not in the DataGridView itself. Now I guess this question is a clunker. – Tom Bogle Jul 18 '12 at 14:44

0 Answers0