Multiline input in Winforms DataGrid

The problem: how to configure Datagrid so that it would be able to accept multiline inputs in their standard TextBox cells? The first thing is to make RowHight large enough to be able to see more than one line in a cell. The property Multiline is set to true per default, so we don’t need to change it.
 
It still remain however the problem of creating new lines with press “Enter”-key. The standard behaviour at DataGrid is to jump to the next cell, so it arose the question how to catch and redirect this event?
 
That should be easy I thought and wasted hours to find the solution. At first in Google, then by myself. Just found it:
 
I use the ordinary method to do such things: derive a new control and override the protected methode ProcessCmdKey. The clue is not to use SendKeys.send (“{Enter}”)  because it is apparently redirected back to the grid, but to modify the Text property of the underlying Text control directly. Here is the code snippet that does the job:

[C#]

public class OLDataGrid : System.Windows.Forms.DataGrid
{


  protected override System.Boolean ProcessCmdKey (ref Message msg, Keys keyData)
  {
    if ((msg.WParam.ToInt32() == (int) Keys.Enter))
    {
      int column = this.CurrentCell.ColumnNumber;
      DataGridTextBoxColumn myTextBoxColumn = null;
      foreach (DataGridTableStyle currTableStyle in TableStyles)
      if (this.DataMember == currTableStyle.MappingName)
      {
         myTextBoxColumn =
           (DataGridTextBoxColumn) currTableStyle.GridColumnStyles[column];
         break;
      };
      if (myTextBoxColumn != null)
        myTextBoxColumn.TextBox.AppendText("\x0D\x0A");
      return true;
    }
    else
      return base.ProcessCmdKey(ref msg, keyData);
  }
}

The grid must be bound and use TableStyle(s) because only then AFAIK the underlying Text control can be accessed. It can use more than one Tablestyles: the grid will automatically check if the current column exists in the chosen TableStyle to prevent AV.

PS It's my first article here and I would be pleased to receive feedback!

 

Share this article!

Follow us!

Find more helpful articles: