It is nearly impossible to solve this request by using only the "standard events". Especially handling of ENTER while the grid is in edit mode I don't see how to solve this.
Therefore I suggest to solve the request by introducing your own grid derived from
DataGridView
. On a first glance it would maybe sound difficult, but please don't be afraid, it is easier than you think.
Also an advantage of this approach is, you can use your "new" grid in any form/app without the need of reimplement all this key up/down etc. handlers. Finally you will learn some Basics/get a feeling how to make your own Controls.
To make it easier at the beginning I recommend to add that user control first in a small test project to test and adapt it for your requirements. After you are happy with the control you can later move it to a seperate assembly and use it in any of your project.
Most Information for the Special ENTER handling I found here:
https://msdn.microsoft.com/query/dev11.query?appId=Dev11IDEF1&l=DE-DE&k=k(System.Windows.Forms.DataGridView.ProcessDialogKey);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5);k(DevLang-csharp)&rd=true[
^]
public class DataGridViewX : DataGridView
{
public bool DefaultEnterKeyBehavior { get; set; }
public DataGridViewX()
{
DefaultEnterKeyBehavior = true;
}
[System.Security.Permissions.UIPermission(
System.Security.Permissions.SecurityAction.LinkDemand,
Window = System.Security.Permissions.UIPermissionWindow.AllWindows)]
protected override bool ProcessDialogKey(Keys keyData)
{
Keys key = (keyData & Keys.KeyCode);
if (DefaultEnterKeyBehavior || (key != Keys.Enter))
{
return base.ProcessDialogKey(keyData);
}
return false;
}
[System.Security.Permissions.SecurityPermission(
System.Security.Permissions.SecurityAction.LinkDemand, Flags =
System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode)]
protected override bool ProcessDataGridViewKey(KeyEventArgs e)
{
if (DefaultEnterKeyBehavior || (e.KeyCode != Keys.Enter))
{
return base.ProcessDataGridViewKey(e);
}
else
{
if (this.CurrentCell.ColumnIndex < (this.ColumnCount - 1))
{
this.ProcessRightKey(e.KeyData);
}
else if (this.CurrentCell.RowIndex < (this.RowCount - 1))
{
this.ProcessHomeKey(e.KeyData);
this.ProcessDownKey(e.KeyData);
}
else
{
SendKeys.Send("{TAB}");
}
return true;
}
}
}
A remark to the multiply
return
in the methods:
Usually I avoid to have multiply
return
statements in a method. But in this case -whyever- for me the code is easier to read with them...
Final remarks:
- When using the new grid dont't Forget to set the property
DefaultEnterKeyBehavior
to false, either in designer or in code.
- For background information about creating user controls for .NET you will find a lot of tutorials by google.
- Try to find a better name than DataGridViewX :)
I hope it helps.