Capturing Return / Enter in DataGridViewTextBoxCell’s in a DataGridView

By default the DataGridView will move to the cell below whenever the user presses the return key and the only way for a user to add a new line to a text box cell, if the column’s style WrapMode has been set to true, is to press SHIFT+ENTER.
For many users editing a multiline field in a DataGridView this behaviour can be annoying and counter-intuitive but changing this behaviour is not just as simple as adding a KeyDown / KeyPress event handler.

To Change the default behaviour of the DataGridView’s response to the key press we must implement a new class which is derived from DataGridView and then override the ProcessCmdKey member, allowing us to intercept the message before the DataGridView applies its logic and apply our own.

For the application I am working I wanted a new line to be created when the user pressed the return key instead of moving to the next row if the user was editing a text box cell and the cell’s WrapMode was true. The following code is what we’re using at the moment in one of our applications:

	public class MultiLineDataGridView : DataGridView
		protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
			if (this.CurrentCell is DataGridViewTextBoxCell &&
				this.CurrentCell.IsInEditMode &&
				(keyData == Keys.Enter || keyData == Keys.Return))
				return true;
				return base.ProcessCmdKey(ref msg, keyData);

While I’m no fan of using SendKeys and would much rather modify the key code being processed by the application it turns out that in this case the DataGridView responds better to having the key event triggered as if the user had initiated it themselves and will create new lines in Word Wrapped text box cells but apply its default behaviour (and move to the next row) on any other cell.


About tc

tc is a Hull based Computer Programmer with over 15 years experience in Software Development. He has developed countless Multi-Tear Desktop Applications and web applications for business in both the UK and abroad. Currently tc spends most of his time developing web sites / applications in PHP and desktop software in C#
This entry was posted in .NET. Bookmark the permalink.

Comments are closed.