I want to only allow the user to enter 0..9, "." and backspace in my DGV. I thought the KeyDown event might be the ticket, with something like this:
private void dataGridViewPlatypi_KeyDown(object sender, KeyEventArgs args)
{
args.Handled = !args.KeyCode.Equals(Keys.Decimal); // etc. - add other allowed vals
if (args.Handled)
{
args.SuppressKeyPress = true;
}
}
...but that doesn't work/has no effect.
I researched and found this: DataGridView keydown event not working in C#
...which led me to creating a custom DGV class with this:
protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData)
{
if ((!keyData.Equals(Keys.Decimal)) &&
(!keyData.Equals(Keys.???))) // etc.
{
//suppress the key somehow
}
return base.ProcessCmdKey(msg, keyData); // <-- should this be in an "else" block?
}
...but as you can tell from the "???" and the "somehow" comment, I don't know how to test for the other keys I want to allow (0..9 and backspace)
UPDATE
With able assistance from two respondents, it's now working just great:
I started off with Hans Passant's code here to create a custom DGV-derived control to solve the moveable final row problem:
removing the empty gray space in datagrid in c#
...and then added code based on LarsTech's to filter out unwanted entries in the DGV.
To be precise, this is the exact logic I used to override ProcessCmdKey():
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (char.IsNumber(Convert.ToChar(keyData)) ||
char.IsControl(Convert.ToChar(keyData)) ||
(keyData >= Keys.NumPad0 && keyData <= Keys.NumPad9) ||
(keyData == Keys.Space) ||
(keyData == Keys.Back) ||
(keyData == Keys.Decimal))
{
return false;
}
return true;
}